### Replication code for Hainmueller, Hall, and Snyder
### Note that this file produces only a portion of the analyses in the paper
### The remaing portion are produced in the accompanying Stata do file
rm(list=ls())

### set working directory here
setwd("~/Dropbox/RDD_Extrapolate")

### set seed
set.seed(1234)

### make sure to install these if necessary
library(Matching)
library(ebal)
library(foreign)
library(sandwich)
library(lmtest)
library(survey)
library(Hmisc)
library(rbounds)

### This code will produce results for main (Dem) effects

### parameters for smoothed plot
x.size <- 40
span.x <- .5

# load cleaned data
d <- read.dta("statewide_analysis.dta")
d <- d[order(d$treat),]

# control sets
controlsets <- list()
controlsets[[1]] <- c("lag","lag2","lag_norm_vote","lag_norm_vote2","midterm")
controlsets[[2]] <- controlsets[[1]][-4]
controlsets[[3]] <- controlsets[[1]][c(1,3)]

# partial residual plots

# bandwidth
dsub <- na.omit(
  d[abs(d$rv)<x.size,
    c("dv","treat","rv",controlsets[[1]])
    ]
)

dsub <- dsub[order(dsub$rv),]

dsubright <- dsub[dsub$rv>0,]
dsubleft  <- dsub[dsub$rv<0,]

form1 <- as.formula(
  paste("dv~rv+",
        paste(controlsets[[1]],collapse="+")
  )
)

out    <- lm(form1,data=dsubright)
dsubright$CRresid <- out$resid + coef(out)["rv"]*dsubright$rv

out    <- lm(form1,data=dsubleft)
dsubleft$CRresid <- out$resid + coef(out)["rv"]*dsubleft$rv

dsub <- rbind(dsubleft,dsubright)

pdf("Table2FigA.pdf",width=9,height=7)
op <- par(mfrow = c(1,2),
          oma = c(5,4,0,0) + 0.1,
          mar = c(0,0,1,1) + 0.1)

plot(y=dsubleft$CRresid,dsubleft$rv,
     xlab="Democratic Margin (%)",
     ylab="Component + Residual: Democratic Margin (%)",cex=.6,
     ylim=c(-40,40),axes = FALSE,xaxs="r",yaxs="i",main="Losers (D=0)", col="gray70")

axis(side = 1,
     at=seq(-x.size,0,5),labels=seq(-x.size,0,5))
     
axis(side = 2, at = seq(-40,40,20) )
segments(x0=0,y0=-40,y1=40)
segments(x0=-x.size-5,x1=0,y0=40,y1=40)
segments(x0=-x.size-5,x1=0,y0=-40,y1=-40)

lo <- predict(loess(CRresid ~ rv, dsubleft ,span=span.x),se=TRUE)
lines(y=lo$fit,dsubleft$rv,lwd=3,col="black")
lines(y=lo$fit+2*lo$se.fit,dsubleft$rv,lwd=2,col="black",lty=2)
lines(y=lo$fit-2*lo$se.fit,dsubleft$rv,lwd=2,col="black",lty=2)
legend("bottomleft",legend=c("Loess Line"),lty=1,lwd=2,col="black")

plot(y=dsubright$CRresid,dsubright$rv,
     xlab="Democratic Margin (%)",
     ylab="",cex=.6,ylim=c(-40,40),axes = FALSE,xaxs="r",yaxs="i",main="Winners (D=1)", col="gray70")

axis(side = 1,
     at=seq(0,x.size,5),labels=seq(0,x.size,5))

segments(x0=0,y0=-40,y1=40)
segments(x0=0,x1=x.size,y0=40,y1=40)
segments(x0=0,x1=x.size,y0=-40,y1=-40)
segments(x0=x.size,x1=x.size,y0=-40,y1=40)

lo <- predict(loess(CRresid ~ rv, dsubright ,span=span.x),se=TRUE)
lines(y=lo$fit,dsubright$rv,lwd=3,col="black")
lines(y=lo$fit+2*lo$se.fit,dsubright$rv,lwd=2,col="black",lty=2)
lines(y=lo$fit-2*lo$se.fit,dsubright$rv,lwd=2,col="black",lty=2)

title(xlab = "Democratic Margin (%)",
      ylab = "Component + Residual: Democratic Margin (%)",
      outer = TRUE, line = 3)

dev.off()


# effect estimates
biggeststore <- list()
bigbalstore <- list()
biggammastore <- list()

for(h in 1:4){
  bw <- seq(5,20,5)[h]
  bigstore <- list()
  balstore <- list()
  gammastore <- list()
  
 for(i in 1:3){

  # bandwidth
  dsub <- na.omit(
                  d[abs(d$rv)<bw,
                     c("dv","treat","rv",controlsets[[i]])
                    ]
                  )
  
  store <- matrix(NA,3,3)
  rownames(store) <- c("OLS","Match","Ebal")
  colnames(store) <- c("PE","SE","N")
  
  # regressions
  form <- as.formula(
                     paste("dv~treat+",
                           paste(controlsets[[i]],collapse="+")
                          )
                    )
  out <- lm(form,data=dsub)
  store[1,1:3] <- c(coeftest(out,vcov = vcovHC(out, type = "HC1"))[2,1:2],
                    length(out$residuals)
                    )
  
  # NN Matching
  g.weights <- GenMatch(Tr=dsub$treat, X=dsub[,controlsets[[i]]],estimand="ATT", M=1,
                        print.level=0,pop.size=1000)
  out <- Match(Y=dsub$dv, Tr=dsub$treat, X=dsub[,controlsets[[i]]],Weight.matrix=g.weights,
         estimand = "ATT", M = 1,
         BiasAdjust = TRUE, replace=TRUE, ties=TRUE,
         Var.calc = 1)
  store[2,1:3] <- c(out$est,out$se,out$nobs)
  
  # sensitivity
  hl <- hlsens(out, Gamma=10, GammaInc=.1)
  ph <- psens(out, Gamma=10, GammaInc=.1)
  
  # extract highest Gamma at which lower bound of HL estimate is above zero
  # extract highest Gamma at which upper bound of p-value is below .10
  gammas <- c(
    hl$bounds[hl$bounds[,"Lower bound"] > 0,"Gamma"][length(hl$bounds[hl$bounds[,"Lower bound"] > 0,"Gamma"])],
    ph$bounds[ph$bounds[,"Upper bound"] < 0.1,"Gamma"][length(ph$bounds[ph$bounds[,"Upper bound"] < 0.1,"Gamma"])]
    )
  
  
   # Balance Stats
    balform <- as.formula(
     paste("treat~",
          paste(controlsets[[i]],collapse="+")
     )
    )
    bout <- MatchBalance(balform,data=dsub,match.out=out)
    bout <- data.frame(rbind(
         baltest.collect(matchbal.out=bout,var.names=controlsets[[i]],after=FALSE),
         baltest.collect(matchbal.out=bout,var.names=controlsets[[i]],after=TRUE)
         ),var=rep(controlsets[[i]],2),type=c(
                                              rep("Unmatched",length(controlsets[[i]])),
                                              rep("Matched",  length(controlsets[[i]]))
                                              ),row.names = NULL)
  
  # ebalance
  out <- ebalance(Treatment=dsub$treat,X=dsub[,controlsets[[i]]])
  
  dsub$w <- c(out$w,rep(1,sum(dsub$treat)))
  summary(out$w)
  des <- svydesign(id=~1,weights=dsub$w, data=dsub)
  out <- svyglm(dv ~ treat, design = des)
  summary(out)
  store[3,1:3] <-  c(summary(out)$coef[2,1:2],
                     length(out$residuals))

    # balance stats
   bout.eb <- MatchBalance(balform,data=dsub,weights=dsub$w,ks=TRUE)
   bout.eb <- data.frame(baltest.collect(matchbal.out=bout.eb,                                    
                                         var.names=controlsets[[i]],after=FALSE),
              var=controlsets[[i]],
              type=rep("Reweighted",length(controlsets[[i]])),
                         row.names = NULL
                         )
   bout <- rbind(bout,bout.eb)  
   balstore[[i]] <- bout
   bigstore[[i]] <- store
   gammastore[[i]] <- gammas
  
  } # close loop over bandwith
  names(balstore) <- paste("Set",1:3)
  bigbalstore[[h]] <- balstore
  
  names(bigstore) <- paste("Set",1:3)
  biggeststore[[h]] <- bigstore
 
 names(gammastore) <- paste("Set",1:3)
 biggammastore[[h]] <- gammastore
 
} # close loop over controlsets

names(bigbalstore) <- paste("W",seq(5,20,5))
bal <- bigbalstore

names(biggeststore) <- paste("W",seq(5,20,5))
b <- biggeststore

names(biggammastore) <- paste("W",seq(5,20,5))
biggammastore

save.image("Results.RData")

# RDD estimates as a benchmark
bw <- c(1,2,5,10)
# othervars that should not be missing to make sample comparable
RDlist <- list()

store <- matrix(NA,length(controlsets),3)
rownames(store) <- paste("control set",1:3,sep="")
colnames(store) <- c("PE","SE","N")

for(h in 1:length(bw)){

for(i in 1:3){
dsub <- na.omit(
  d[abs(d$rv)< bw[h],
    c("dv","treat","rv","rv_treat",controlsets[[i]])
    ]
)

out <- lm("dv~treat+rv+rv_treat",data=dsub)
store[i,1:3] <- c(coeftest(out,vcov = vcovHC(out, type = "HC1"))[2,1:2],
                  length(out$residuals))
}
RDlist[[h]] <- store
}
names(RDlist) <- bw




# create table
cat(
  c("\\begin{table}[ht]
    \\centering
    \\caption{{\\bf Incumbency Effects in Less Competitive Districts and at the Threshold.} \\label{estimatesDem} The top panel presents incumbency effect estimates in less competitive districts based on the conditional independence assumption for different windows and covariate adjustment methods. The bottom panel presents for comparison the incumbency effect estimates at the threshold based on a regression discontinuity design for different bandwidths.}
     \\begin{tabular}{cccccccccc}
    \\toprule \\toprule
  \\multicolumn{10}{l}{\\bf Incumbency Effect in Less Competitive Districts} \\\\
\\midrule
   & \\multicolumn{3}{c}{\\bf Control Set 1:} & \\multicolumn{3}{c}{\\bf Control Set 2:} & \\multicolumn{3}{c}{\\bf Control Set 3:} \\\\
   & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } \\\\
   & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } \\\\
   & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{3}{c}{  } \\\\
   & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{3}{c}{  } \\\\
   & \\multicolumn{3}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{3}{c}{  } & \\multicolumn{3}{c}{  } \\\\[2mm]
    Window  & OLS & Match & Weight & OLS & Match & Weight & OLS & Match & Weight\\\\
    \\midrule
    5 &",sprintf("%.2f", round(b[["W 5"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 1"]]["Ebal","PE"],2)),
     "&",sprintf("%.2f", round(b[["W 5"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 2"]]["Ebal","PE"],2)),
     "&",sprintf("%.2f", round(b[["W 5"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
      &",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
     "&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
     "&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
      &",paste("\\emph{N=",b[["W 5"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 1"]]["Ebal","N"],"}",sep=""),
     "&",paste("\\emph{N=",b[["W 5"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 2"]]["Ebal","N"],"}",sep=""),
     "&",paste("\\emph{N=",b[["W 5"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\[2mm]
  10 &",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
      &",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
     "&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
     "&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
      &",paste("\\emph{N=",b[["W 10"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 1"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 10"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 2"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 10"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\[2mm]   
  15 &",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
     &",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
      &",paste("\\emph{N=",b[["W 15"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 1"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 15"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 2"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 15"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\[2mm]
  \\midrule \\midrule
  \\multicolumn{10}{l}{\\bf Incumbency Effect at the Threshold (RD estimates)} \\\\
  \\midrule
  Bandwidth & \\multicolumn{3}{c}{Local Linear}  & \\multicolumn{3}{c}{Local Linear} & \\multicolumn{3}{c}{Local Linear} \\\\
  \\midrule 
1 & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["1"]]["control set1","PE"],2)),"}& \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["1"]]["control set2","PE"],2)),"}  & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["1"]]["control set3","PE"],2)),"} \\\\
 &  \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["1"]]["control set1","SE"],2)),")",sep=""),"}& \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["1"]]["control set2","SE"],2)),")",sep=""),"}  & \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["1"]]["control set3","SE"],2)),")",sep=""),"} \\\\
 &  \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["1"]]["control set1","N"],"}",sep=""),"}& \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["1"]]["control set2","N"],"}",sep=""),"}  & \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["1"]]["control set3","N"],"}",sep=""),"} \\\\[2mm]
2 & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["2"]]["control set1","PE"],2)),"}& \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["2"]]["control set2","PE"],2)),"}  & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["2"]]["control set3","PE"],2)),"} \\\\
 &  \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["2"]]["control set1","SE"],2)),")",sep=""),"}& \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["2"]]["control set2","SE"],2)),")",sep=""),"}  & \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["2"]]["control set3","SE"],2)),")",sep=""),"} \\\\
 &  \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["2"]]["control set1","N"],"}",sep=""),"}& \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["2"]]["control set2","N"],"}",sep=""),"}  & \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["2"]]["control set3","N"],"}",sep=""),"} \\\\[2mm]
5 & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["5"]]["control set1","PE"],2)),"}& \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["5"]]["control set2","PE"],2)),"}  & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["5"]]["control set3","PE"],2)),"} \\\\
 &  \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["5"]]["control set1","SE"],2)),")",sep=""),"}& \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["5"]]["control set2","SE"],2)),")",sep=""),"}  & \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["5"]]["control set3","SE"],2)),")",sep=""),"} \\\\
 &  \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["5"]]["control set1","N"],"}",sep=""),"}& \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["5"]]["control set2","N"],"}",sep=""),"}  & \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["5"]]["control set3","N"],"}",sep=""),"} \\\\[2mm]
\\bottomrule
    \\multicolumn{10}{p{.95\\textwidth}}{\\footnotesize Covariate adjustments are: OLS - Linear regression; Match: One-to-one nearest neighbor matching with replacement and bias adjustment; Weight: Entropy balancing; Local linear: Local linear RD regression. Robust standard errors in parentheses. Window: Sample used to estimate the effect by comparing winners and losers. Bandwidth: Sample used to estimate the RD effect at the threshold. $Y_{i,t+1}$ measured in percentage points, 0--100. }
    \\end{tabular}
    \\end{table}"
    ),file="estimates.tex"
  )
  
# estimates figure
# control sets
figlist <- list()
windows <- seq(1,15,1)

for(i in 1:3){

  store <- matrix(NA,length(windows),3)
  rownames(store) <- windows
  colnames(store) <- c("PE","SE","N")

  
for(h in 1:length(windows)){
  
    # bandwidth
    bw <- windows[h]
    dsub <- na.omit(
      d[abs(d$rv)<bw,
        c("dv","treat","rv",controlsets[[i]])
        ]
    )
    
    # regressions
    form <- as.formula(
      paste("dv~treat+",
            paste(controlsets[[i]],collapse="+")
      )
    )
    out <- lm(form,data=dsub)
    store[h,1:2] <- coeftest(out,vcov = vcovHC(out, type = "HC1"))[2,1:2]
    store[h,3]   <- length(out$residuals)
    
  } 
figlist[[i]] <- store
}

dfig <- figlist[[1]]

pdf("Table3Fig1.pdf",width=9,height=7)
plot(y=dfig[,"PE"],x=windows,pch=19,
     ylim=c(0,12),
     xlim=c(0,15),
     ylab=c("Incumbency Effect Estimate (%)"),
     xlab=c("Effect Window (%)"),
     xaxt="n"
  )
axis(side=1,at=seq(min(windows),max(windows),length.out=length(windows)))

arrows(windows, dfig[,"PE"]-2*dfig[,"SE"]
      ,windows, dfig[,"PE"]+2*dfig[,"SE"]
      , length = 0.15, angle = 90,
       code = 3)

points(y=RDlist[["5"]]["control set1","PE"],
       x=0,pch=15,col="red")

arrows(0, RDlist[["5"]]["control set1","PE"]-2*RDlist[["5"]]["control set1","SE"]
       ,0, RDlist[["5"]]["control set1","PE"]+2*RDlist[["5"]]["control set1","SE"]
       , length = 0.15, angle = 90,col="red",
       code = 3)


arrows(0.1, 4.75
       ,1, 2.5
       , length = 0.10, angle = 35,col="black",
       code = 1)

text(1,2.5,label="RD Estimate at Threshold",pos=4)
dev.off()

## balance stats 
library(tables)
controlsetslab <- list()
controlsetslab[[1]] <- c("Dem Share t-1","Dem Share t-2",
                         "Normal Votet t-1","Normal Vote t-2",
                         "Midterm Slump t")
controlsetslab[[2]] <- controlsetslab[[1]][-4]
controlsetslab[[3]] <- controlsetslab[[1]][c(1,3)]


showvars <- c("type","var","mean.Tr","mean.Co","sdiff.pooled","T.pval","var.ratio")
tab <- bigbalstore[["W 5"]][["Set 1"]][,showvars]
tab$var <- rep(controlsetslab[[1]],3)
tab$type <- rep(c("Unmatched","After Genetic Matching","After Entropy Balancing"),
                each=length(controlsetslab[[1]]))

tab$sdiff.pooled <- tab$sdiff.pooled/100
tab[,-c(1:2)] <- round(tab[,-c(1:2)],2)
colnames(tab) <- c("Adjustment","Covariate","Mean Tr","Mean Co","S.Diff","T.pval","Var.Ratio")


latex(tab,
      file="baltable5.tex",
      #file="",
      label="balancetable5",
      #title='',
      dec=2,rowname=NULL,
      caption=c("Balance Before and After Covariate Adjustment (Window 5\\%)"),
      align=c("llccccc"),
      insert.bottom=c("S.Diff=Standardized difference in means; T-pval=p-value from difference in means test; Var.Ratio: Ratio of variances"))


tab <- bigbalstore[["W 10"]][["Set 1"]][,showvars]
tab$var <- rep(controlsetslab[[1]],3)
tab$type <- rep(c("Unmatched","After Genetic Matching","After Entropy Balancing"),
                each=length(controlsetslab[[1]]))

tab$sdiff.pooled <- tab$sdiff.pooled/100
tab[,-c(1:2)] <- round(tab[,-c(1:2)],2)
colnames(tab) <- c("Adjustment","Covariate","Mean Tr","Mean Co","S.Diff","T.pval","Var.Ratio")

latex(tab,
      file="baltable10.tex",
      #file="",
      label="balancetable10",
      #title='',
      dec=2,rowname=NULL,
      caption=c("Balance Before and After Covariate Adjustment (Window 10\\%)"),
      align=c("llccccc"),
      insert.bottom=c("S.Diff=Standardized difference in means; T-pval=p-value from difference in means test; Var.Ratio: Ratio of variances"))
dev.off()

# plots
library(lattice)


mypal<-c("black","darkgrey","darkgrey")
Cex <- Cex2 <- 1

# plot with SDs
bplot <- function(x,y,...)
{
  panel.abline(v=0, lwd = 1 , lty="solid")
  panel.abline(v=c(-.1,.1), lwd = 2 , lty="dotted")
  panel.abline(h=c(1:nrow(d)), lwd = 1 , lty="dashed", col="gray95")
  panel.xyplot(x,y,...)
}

bplot2 <- function(x,y,...)
{
  panel.abline(v=c(0,1), lwd = 1 , lty="solid")
  panel.abline(v=c(.05,.1), lwd = 1 , lty="dotted")
  panel.abline(h=c(1:nrow(d)), lwd = 1 , lty="dashed", col="gray95")
  panel.xyplot(x,y,...)
}

for(i in c(5,10,15,20)){
  for(s in 1:3){
    
dbal      <- bal[[paste("W",i)]][[paste("Set",s)]]
dbal$type <- factor(dbal$type,levels=unique(dbal$type))
dbal$var  <- factor(dbal$var,levels=unique(dbal$var)[length(unique(dbal$var)):1],
                    labels=controlsetslab[[1]][length(unique(dbal$var)):1])


# plot with Sds
pdf(paste("balSDw",i,"s",s,".pdf",sep=""),width=7,height=7,pointsize=13)
print(
  xyplot(var~round(sdiff.pooled/100,2),data=dbal,groups=type,xlim=c(-.6,.6),
         panel = bplot
         ,par.settings = list(superpose.symbol = list(pch = c(15,19,17),col=mypal,cex=1.5))
         ,xlab=list("standardized difference in means",cex=Cex),ylab="",
         auto.key=T,scales=list(
           y=list(cex=Cex),
           x=list(cex=Cex2,at=c(-.5,-.1,0,.1,.5),labels=c("-.5","-.1","0",".1",".5")))
  )
)
dev.off()

pdf(paste("balpvalw",i,"s",s,".pdf",sep=""),width=7,height=7,pointsize=13)
# plot with p-values
print(
  xyplot(var~round(T.pval,2),data=dbal,groups=type,xlim=c(-.05,1.05),
         panel = bplot2
         ,par.settings = list(superpose.symbol = list(pch = c(15,19,17),col=mypal,cex=1.5))
         ,xlab=list("p-value: difference of means test",cex=Cex),ylab="",
         auto.key=T,scales=list(
           y=list(cex=Cex),
           x=list(cex=Cex2,at=c(0,.05,.1,.5,1),labels=c("0",".05",".1",".5","1")))
  )
)
dev.off()
  }
}

## Table with Gammas

ga <- biggammastore

cat(
  c("\\begin{table}[ht]
    \\centering
    \\caption{{\\bf Sensitivity Analysis for Incumbency Effects in Less Competitive Districts.} \\label{Gamma} Table presents Gamma values from Rosenbaum sensitivity tests for the matching based estimates of the incumbency effects presented in Table 4. The reported Gamma values measure the degree of hidden bias from an unobserved confounder at which the effect estimates would turn insignificant.}
    \\begin{tabular}{ccccccc}
    \\toprule \\toprule
    \\multicolumn{7}{l}{\\bf Sensitivity of Incumbency Effect Estimates in Less Competitive Districts} \\\\
    \\midrule
    & \\multicolumn{2}{c}{\\bf Control Set 1:} & \\multicolumn{2}{c}{\\bf Control Set 2:} & \\multicolumn{2}{c}{\\bf Control Set 3:} \\\\
    & \\multicolumn{2}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{2}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{2}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } \\\\
    & \\multicolumn{2}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{2}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{2}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } \\\\
    & \\multicolumn{2}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{2}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{2}{c}{  } \\\\
    & \\multicolumn{2}{c}{ $\\mathit{Normal \\ Vote}_{t-2}$ } & \\multicolumn{2}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{2}{c}{  } \\\\
    & \\multicolumn{2}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{2}{c}{  } & \\multicolumn{2}{c}{  } \\\\[2mm]
Window  &  Gamma HL  & Gamma p-val & Gamma HL  & Gamma p-val & Gamma HL  & Gamma p-val\\\\
    \\midrule
    5 &",sprintf("%.2f", round(ga[["W 5"]][["Set 1"]][1],2)),"&",sprintf("%.2f",round(ga[["W 5"]][["Set 1"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 5"]][["Set 2"]][1],2)),"&",sprintf("%.2f",round(ga[["W 5"]][["Set 2"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 5"]][["Set 3"]][1],2)),"&",sprintf("%.2f",round(ga[["W 5"]][["Set 3"]][2],2)),"\\\\[2mm]
    10 &",sprintf("%.2f", round(ga[["W 10"]][["Set 1"]][1],2)),"&",sprintf("%.2f", round(ga[["W 10"]][["Set 1"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 10"]][["Set 2"]][1],2)),"&",sprintf("%.2f", round(ga[["W 10"]][["Set 2"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 10"]][["Set 3"]][1],2)),"&",sprintf("%.2f", round(ga[["W 10"]][["Set 3"]][2],2)),"\\\\[2mm]   
    15 &",sprintf("%.2f", round(ga[["W 15"]][["Set 1"]][1],2)),"&",sprintf("%.2f", round(ga[["W 15"]][["Set 1"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 15"]][["Set 2"]][1],2)),"&",sprintf("%.2f", round(ga[["W 15"]][["Set 2"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 15"]][["Set 3"]][1],2)),"&",sprintf("%.2f", round(ga[["W 15"]][["Set 3"]][2],2)),"\\\\
\\bottomrule
    \\multicolumn{7}{p{.95\\textwidth}}{\\footnotesize Gamma HL: The lowest Rosenbaum Gamma at which the lower bound of the Hodges-Lehman point estimate of the incumbency effect remains above zero. Gamma p-val: The lowest Rosenbaum Gamma at which the upper bound of the p-value from a Wilcoxon Sign Rank Test turns insignificant. Window: Sample used to estimate the effect by comparing winners and losers.}
    \\end{tabular}
    \\end{table}"
  ),file="gammas.tex"
  )








### Robustness Check ATTs excluding window 0-5


# effect estimates
biggeststore <- list()
bigbalstore <- list()

for(h in 1:3){
  bwUB <- c(10,15,15)[h]
  bwLB <- c(5,5,10)[h]
  bigstore <- list()
  balstore <- list()
  
  for(i in 1:3){
    
    # bandwidth
    dsub <- na.omit(
      d[ (d$rv > -10 & d$rv < 0) | (d$rv > bwLB & d$rv < bwUB)  ,
        c("dv","treat","rv",controlsets[[i]])
        ]
    )
    
    store <- matrix(NA,3,3)
    rownames(store) <- c("OLS","Match","Ebal")
    colnames(store) <- c("PE","SE","N")
    
    # regressions
    form <- as.formula(
      paste("dv~treat+",
            paste(controlsets[[i]],collapse="+")
      )
    )
    out <- lm(form,data=dsub)
    store[1,1:3] <- c(coeftest(out,vcov = vcovHC(out, type = "HC1"))[2,1:2],
                      length(out$residuals)
    )
    
    # NN Matching
    g.weights <- GenMatch(Tr=dsub$treat, X=dsub[,controlsets[[i]]],estimand="ATT", M=1,print.level=0,pop.size=500)
    out <- Match(Y=dsub$dv, Tr=dsub$treat, X=dsub[,controlsets[[i]]],Weight.matrix=g.weights,
                 estimand = "ATT", M = 1,
                 BiasAdjust = TRUE, replace=TRUE, ties=TRUE,
                 Var.calc = 1)
    store[2,1:3] <- c(out$est,out$se,out$nobs)
    
    # Balance Stats
    balform <- as.formula(
      paste("treat~",
            paste(controlsets[[i]],collapse="+")
      )
    )
    bout <- MatchBalance(balform,data=dsub,match.out=out)
    bout <- data.frame(rbind(
      baltest.collect(matchbal.out=bout,var.names=controlsets[[i]],after=FALSE),
      baltest.collect(matchbal.out=bout,var.names=controlsets[[i]],after=TRUE)
    ),var=rep(controlsets[[i]],2),type=c(
      rep("Unmatched",length(controlsets[[i]])),
      rep("Matched",  length(controlsets[[i]]))
    ),row.names = NULL)
    
    # ebalance
    out <- ebalance(Treatment=dsub$treat,X=dsub[,controlsets[[i]]])
    
    dsub$w <- c(out$w,rep(1,sum(dsub$treat)))
    summary(out$w)
    des <- svydesign(id=~1,weights=dsub$w, data=dsub)
    out <- svyglm(dv ~ treat, design = des)
    summary(out)
    store[3,1:3] <-  c(summary(out)$coef[2,1:2],
                       length(out$residuals))
    
    # balance stats
    bout.eb <- MatchBalance(balform,data=dsub,weights=dsub$w,ks=TRUE)
    bout.eb <- data.frame(baltest.collect(matchbal.out=bout.eb,                                    
                                          var.names=controlsets[[i]],after=FALSE),
                          var=controlsets[[i]],
                          type=rep("Reweighted",length(controlsets[[i]])),
                          row.names = NULL
    )
    bout <- rbind(bout,bout.eb)  
    balstore[[i]] <- bout
    
    bigstore[[i]] <- store
    
  } # close loop over bandwith
  names(balstore) <- paste("Set",1:3)
  bigbalstore[[h]] <- balstore
  
  names(bigstore) <- paste("Set",1:3)
  biggeststore[[h]] <- bigstore
} # close loop over controlsets

names(bigbalstore) <- paste("W",c("5.10","5.15","10.15"))
bal <- bigbalstore

names(biggeststore) <- paste("W",c("5.10","5.15","10.15"))
b <- biggeststore





# create table
cat(
  c("\\begin{table}[ht]
    \\centering
    \\caption{{\\bf  Incumbency Effects in Less Competitive Districts Further Away from the Threshold.} \\label{externalVal} Presents incumbency effect estimates in less competitive districts based on the conditional independence assumption for different margins and covariate adjustment methods. The estimates are based on districts where the winners won with margins between 5-10\\%, 5-15\\%, or 10-15\\% and excludes districts where the winner won with narrower margins.}
    \\begin{tabular}{cccccccccc}
    \\toprule \\toprule
   % \\multicolumn{10}{l}{\\bf Incumbency Effect in Less Competitive Districts} \\\\
  %  \\midrule
    & \\multicolumn{3}{c}{\\bf Control Set 1:} & \\multicolumn{3}{c}{\\bf Control Set 2:} & \\multicolumn{3}{c}{\\bf Control Set 3:} \\\\
    & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } \\\\
    & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } \\\\
    & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{3}{c}{  } \\\\
    & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{3}{c}{  } \\\\
    & \\multicolumn{3}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{3}{c}{  } & \\multicolumn{3}{c}{  } \\\\[2mm]
    Margin  & OLS & Match & Weight & OLS & Match & Weight & OLS & Match & Weight\\\\
    \\midrule
    5-10 &",sprintf("%.2f", round(b[["W 5.10"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.10"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.10"]][["Set 1"]]["Ebal","PE"],2)),
        "&",sprintf("%.2f",round(b[["W 5.10"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 5.10"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.10"]][["Set 2"]]["Ebal","PE"],2)),
        "&",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
     &",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
     &",paste("\\emph{N=",b[["W 5.10"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 1"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 5.10"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 2"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 5.10"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\[2mm]
5-15 &",sprintf("%.2f",round(b[["W 5.15"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.15"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 5.15"]][["Set 1"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
     &",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
     &",paste("\\emph{N=",b[["W 5.15"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 1"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 5.15"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 2"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 5.15"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\[2mm]   
10-15 &",sprintf("%.2f",round(b[["W 10.15"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 10.15"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 10.15"]][["Set 1"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
     &",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
     &",paste("\\emph{N=",b[["W 10.15"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 1"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 10.15"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 2"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 10.15"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\
    \\bottomrule
    \\multicolumn{10}{p{.95\\textwidth}}{\\footnotesize Covariate adjustments are: OLS - Linear regression; Match: One-to-one nearest neighbor matching with replacement and bias adjustment; Weight: Entropy balancing. Robust standard errors in parentheses. Margins: Sample of winners used to estimate the effect by comparing winners and losers, e.g. Margin 5-10 means that only districts where the Democrats won with margins between 5 and 10\\% are included. For all margins, the sample of losers consists of districts where the Democrats lost with margins between -10 and 0\\%. $Y_{i,t+1}$ measured in percentage points, 0--100. }
    \\end{tabular}
    \\end{table}"
  ),file="estimatesExternalVal.tex"
  )

# balance stats 
controlsetslab <- list()
controlsetslab[[1]] <- c("Dem Share t-1","Dem Share t-2",
                         "Normal Votet t-1","Normal Vote t-2",
                         "Midterm Slump t")
controlsetslab[[2]] <- controlsetslab[[1]][-4]
controlsetslab[[3]] <- controlsetslab[[1]][c(1,3)]


showvars <- c("type","var","mean.Tr","mean.Co","sdiff.pooled","T.pval","var.ratio")
tab <- bigbalstore[["W 5.10"]][["Set 1"]][,showvars]
tab$var <- rep(controlsetslab[[1]],3)
tab$type <- rep(c("Unmatched","After Genetic Matching","After Entropy Balancing"),
                each=length(controlsetslab[[1]]))

tab$sdiff.pooled <- tab$sdiff.pooled/100
tab[,-c(1:2)] <- round(tab[,-c(1:2)],2)
colnames(tab) <- c("Adjustment","Covariate","Mean Tr","Mean Co","S.Diff","T.pval","Var.Ratio")

latex(tab,
      file="baltable5.10.tex",
      #file="",
      label="balancetable5.10",
      #title='',
      dec=2,rowname=NULL,
      caption=c("Balance Before and After Covariate Adjustment (Margins of 5-10\\%)"),
      align=c("llccccc"),
      insert.bottom=c("S.Diff=Standardized difference in means; T-pval=p-value from difference in means test; Var.Ratio: Ratio of variances"))

tab <- bigbalstore[["W 5.15"]][["Set 1"]][,showvars]
tab$var <- rep(controlsetslab[[1]],3)
tab$type <- rep(c("Unmatched","After Genetic Matching","After Entropy Balancing"),
                each=length(controlsetslab[[1]]))

tab$sdiff.pooled <- tab$sdiff.pooled/100
tab[,-c(1:2)] <- round(tab[,-c(1:2)],2)
colnames(tab) <- c("Adjustment","Covariate","Mean Tr","Mean Co","S.Diff","T.pval","Var.Ratio")

latex(tab,
      file="baltable5.15.tex",
      #file="",
      label="balancetable5.15",
      #title='',
      dec=2,rowname=NULL,
      caption=c("Balance Before and After Covariate Adjustment (Margins 5-15\\%)"),
      align=c("llccccc"),
      insert.bottom=c("S.Diff=Standardized difference in means; T-pval=p-value from difference in means test; Var.Ratio: Ratio of variances"))
dev.off()

tab <- bigbalstore[["W 10.15"]][["Set 1"]][,showvars]
tab$var <- rep(controlsetslab[[1]],3)
tab$type <- rep(c("Unmatched","After Genetic Matching","After Entropy Balancing"),
                each=length(controlsetslab[[1]]))

tab$sdiff.pooled <- tab$sdiff.pooled/100
tab[,-c(1:2)] <- round(tab[,-c(1:2)],2)
colnames(tab) <- c("Adjustment","Covariate","Mean Tr","Mean Co","S.Diff","T.pval","Var.Ratio")

latex(tab,
      file="baltable10.15.tex",
      #file="",
      label="balancetable10.15",
      #title='',
      dec=2,rowname=NULL,
      caption=c("Balance Before and After Covariate Adjustment (Margins 10-15\\%)"),
      align=c("llccccc"),
      insert.bottom=c("S.Diff=Standardized difference in means; T-pval=p-value from difference in means test; Var.Ratio: Ratio of variances"))
dev.off()

##### Below code is for Republican effect estimates


rm(list=ls())
set.seed(1234)

x.size <- 40
span.x <- .5

# load cleaned data
d <- read.dta("statewide_analysis_Rep.dta")
d <- d[order(d$treat),]

# control sets
controlsets <- list()
controlsets[[1]] <- c("lag","lag2","lag_norm_vote","lag_norm_vote2","midterm")
controlsets[[2]] <- controlsets[[1]][-4]
controlsets[[3]] <- controlsets[[1]][c(1,3)]

# partial residual plots

# bandwidth
dsub <- na.omit(
  d[abs(d$rv)<x.size,
    c("dv","treat","rv",controlsets[[1]])
    ]
)

dsub <- dsub[order(dsub$rv),]

dsubright <- dsub[dsub$rv>0,]
dsubleft  <- dsub[dsub$rv<0,]

form1 <- as.formula(
  paste("dv~rv+",
        paste(controlsets[[1]],collapse="+")
  )
)

out    <- lm(form1,data=dsubright)
dsubright$CRresid <- out$resid + coef(out)["rv"]*dsubright$rv

out    <- lm(form1,data=dsubleft)
dsubleft$CRresid <- out$resid + coef(out)["rv"]*dsubleft$rv

dsub <- rbind(dsubleft,dsubright)

#pdf("Table2FigARep.pdf",width=9,height=7)
op <- par(mfrow = c(1,2),
          oma = c(5,4,0,0) + 0.1,
          mar = c(0,0,1,1) + 0.1)

plot(y=dsubleft$CRresid,dsubleft$rv,
     xlab="Republican Margin (%)",
     ylab="Component + Residual: Democratic Margin (%)",cex=.6,
     ylim=c(-40,40),axes = FALSE,xaxs="r",yaxs="i",main="Losers (D=0)", col="gray70")

axis(side = 1,
     at=seq(-x.size,0,5),labels=seq(-x.size,0,5))
     
axis(side = 2, at = seq(-40,40,20) )
segments(x0=0,y0=-40,y1=40)
segments(x0=-x.size-5,x1=0,y0=40,y1=40)
segments(x0=-x.size-5,x1=0,y0=-40,y1=-40)

lo <- predict(loess(CRresid ~ rv, dsubleft ,span=span.x),se=TRUE)
lines(y=lo$fit,dsubleft$rv,lwd=3,col="black")
lines(y=lo$fit+2*lo$se.fit,dsubleft$rv,lwd=2,col="black",lty=2)
lines(y=lo$fit-2*lo$se.fit,dsubleft$rv,lwd=2,col="black",lty=2)
legend("bottomleft",legend=c("Loess Line"),lty=1,lwd=2,col="black")

plot(y=dsubright$CRresid,dsubright$rv,
     xlab="Republican Margin (%)",
     ylab="",cex=.6,ylim=c(-40,40),axes = FALSE,xaxs="r",yaxs="i",main="Winners (D=1)", col="gray70")

axis(side = 1,
     at=seq(0,x.size,5),labels=seq(0,x.size,5))

segments(x0=0,y0=-40,y1=40)
segments(x0=0,x1=x.size,y0=40,y1=40)
segments(x0=0,x1=x.size,y0=-40,y1=-40)
segments(x0=x.size,x1=x.size,y0=-40,y1=40)

lo <- predict(loess(CRresid ~ rv, dsubright ,span=span.x),se=TRUE)
lines(y=lo$fit,dsubright$rv,lwd=3,col="black")
lines(y=lo$fit+2*lo$se.fit,dsubright$rv,lwd=2,col="black",lty=2)
lines(y=lo$fit-2*lo$se.fit,dsubright$rv,lwd=2,col="black",lty=2)

title(xlab = "Republican Margin (%)",
      ylab = "Component + Residual: Republican Margin (%)",
      outer = TRUE, line = 3)

#dev.off()


# effect estimates
biggeststore <- list()
bigbalstore <- list()
biggammastore <- list()

for(h in 1:4){
  bw <- seq(5,20,5)[h]
  bigstore <- list()
  balstore <- list()
  gammastore <- list()
  
 for(i in 1:3){

  # bandwidth
  dsub <- na.omit(
                  d[abs(d$rv)<bw,
                     c("dv","treat","rv",controlsets[[i]])
                    ]
                  )
  
  store <- matrix(NA,3,3)
  rownames(store) <- c("OLS","Match","Ebal")
  colnames(store) <- c("PE","SE","N")
  
  # regressions
  form <- as.formula(
                     paste("dv~treat+",
                           paste(controlsets[[i]],collapse="+")
                          )
                    )
  out <- lm(form,data=dsub)
  store[1,1:3] <- c(coeftest(out,vcov = vcovHC(out, type = "HC1"))[2,1:2],
                    length(out$residuals)
                    )
  
  # NN Matching
  g.weights <- GenMatch(Tr=dsub$treat, X=dsub[,controlsets[[i]]],estimand="ATT", M=1,
                        print.level=0,pop.size=1000)
  out <- Match(Y=dsub$dv, Tr=dsub$treat, X=dsub[,controlsets[[i]]],Weight.matrix=g.weights,
         estimand = "ATT", M = 1,
         BiasAdjust = TRUE, replace=TRUE, ties=TRUE,
         Var.calc = 1)
  store[2,1:3] <- c(out$est,out$se,out$nobs)
  
  # sensitivity
  hl <- hlsens(out, Gamma=10, GammaInc=.1)
  ph <- psens(out, Gamma=10, GammaInc=.1)
  
  # extract highest Gamma at which lower bound of HL estimate is above zero
  # extract highest Gamma at which upper bound of p-value is below .10
  gammas <- c(
    hl$bounds[hl$bounds[,"Lower bound"] > 0,"Gamma"][length(hl$bounds[hl$bounds[,"Lower bound"] > 0,"Gamma"])],
    ph$bounds[ph$bounds[,"Upper bound"] < 0.1,"Gamma"][length(ph$bounds[ph$bounds[,"Upper bound"] < 0.1,"Gamma"])]
    )
  
  
   # Balance Stats
    balform <- as.formula(
     paste("treat~",
          paste(controlsets[[i]],collapse="+")
     )
    )
    bout <- MatchBalance(balform,data=dsub,match.out=out)
    bout <- data.frame(rbind(
         baltest.collect(matchbal.out=bout,var.names=controlsets[[i]],after=FALSE),
         baltest.collect(matchbal.out=bout,var.names=controlsets[[i]],after=TRUE)
         ),var=rep(controlsets[[i]],2),type=c(
                                              rep("Unmatched",length(controlsets[[i]])),
                                              rep("Matched",  length(controlsets[[i]]))
                                              ),row.names = NULL)
  
  # ebalance
  out <- ebalance(Treatment=dsub$treat,X=dsub[,controlsets[[i]]])
  
  dsub$w <- c(out$w,rep(1,sum(dsub$treat)))
  summary(out$w)
  des <- svydesign(id=~1,weights=dsub$w, data=dsub)
  out <- svyglm(dv ~ treat, design = des)
  summary(out)
  store[3,1:3] <-  c(summary(out)$coef[2,1:2],
                     length(out$residuals))

    # balance stats
   bout.eb <- MatchBalance(balform,data=dsub,weights=dsub$w,ks=TRUE)
   bout.eb <- data.frame(baltest.collect(matchbal.out=bout.eb,                                    
                                         var.names=controlsets[[i]],after=FALSE),
              var=controlsets[[i]],
              type=rep("Reweighted",length(controlsets[[i]])),
                         row.names = NULL
                         )
   bout <- rbind(bout,bout.eb)  
   balstore[[i]] <- bout
   bigstore[[i]] <- store
   gammastore[[i]] <- gammas
  
  } # close loop over bandwith
  names(balstore) <- paste("Set",1:3)
  bigbalstore[[h]] <- balstore
  
  names(bigstore) <- paste("Set",1:3)
  biggeststore[[h]] <- bigstore
 
 names(gammastore) <- paste("Set",1:3)
 biggammastore[[h]] <- gammastore
 
} # close loop over controlsets

names(bigbalstore) <- paste("W",seq(5,20,5))
bal <- bigbalstore

names(biggeststore) <- paste("W",seq(5,20,5))
b <- biggeststore

names(biggammastore) <- paste("W",seq(5,20,5))
biggammastore

save.image("ResultsRep.RData")

# RDD estimates as a benchmark
bw <- c(1,2,5,10)
# othervars that should not be missing to make sample comparable
RDlist <- list()

store <- matrix(NA,length(controlsets),3)
rownames(store) <- paste("control set",1:3,sep="")
colnames(store) <- c("PE","SE","N")

for(h in 1:length(bw)){

for(i in 1:3){
dsub <- na.omit(
  d[abs(d$rv)< bw[h],
    c("dv","treat","rv","rv_treat",controlsets[[i]])
    ]
)

out <- lm("dv~treat+rv+rv_treat",data=dsub)
store[i,1:3] <- c(coeftest(out,vcov = vcovHC(out, type = "HC1"))[2,1:2],
                  length(out$residuals))
}
RDlist[[h]] <- store
}
names(RDlist) <- bw




# create table
cat(
  c("\\begin{table}[ht]
    \\centering
    \\caption{{\\bf Incumbency Effects for Republicans in Less Competitive Districts and at the Threshold.} \\label{estimatesReps}The top panel presents incumbency effect estimates in less competitive districts based on the conditional independence assumption for different windows and covariate adjustment methods. The bottom panel presents for comparison the incumbency effect estimates at the threshold based on a regression discontinuity design for different bandwidths.}
     \\begin{tabular}{cccccccccc}
    \\toprule \\toprule
  \\multicolumn{10}{l}{\\bf Incumbency Effect in Less Competitive Districts} \\\\
\\midrule
   & \\multicolumn{3}{c}{\\bf Control Set 1:} & \\multicolumn{3}{c}{\\bf Control Set 2:} & \\multicolumn{3}{c}{\\bf Control Set 3:} \\\\
   & \\multicolumn{3}{c}{ $\\mathit{Rep \\ Share}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Rep \\ Share}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Rep \\ Share}_{t-1}$ } \\\\
   & \\multicolumn{3}{c}{ $\\mathit{Rep \\ Share}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Rep \\ Share}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } \\\\
   & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{3}{c}{  } \\\\
   & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{3}{c}{  } \\\\
   & \\multicolumn{3}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{3}{c}{  } & \\multicolumn{3}{c}{  } \\\\[2mm]
    Window  & OLS & Match & Weight & OLS & Match & Weight & OLS & Match & Weight\\\\
    \\midrule
    5 &",sprintf("%.2f", round(b[["W 5"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 1"]]["Ebal","PE"],2)),
     "&",sprintf("%.2f", round(b[["W 5"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 2"]]["Ebal","PE"],2)),
     "&",sprintf("%.2f", round(b[["W 5"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
      &",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
     "&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
     "&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
      &",paste("\\emph{N=",b[["W 5"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 1"]]["Ebal","N"],"}",sep=""),
     "&",paste("\\emph{N=",b[["W 5"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 2"]]["Ebal","N"],"}",sep=""),
     "&",paste("\\emph{N=",b[["W 5"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\[2mm]
  10 &",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
      &",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
     "&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
     "&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
      &",paste("\\emph{N=",b[["W 10"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 1"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 10"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 2"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 10"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\[2mm]   
  15 &",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
     &",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
      &",paste("\\emph{N=",b[["W 15"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 1"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 15"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 2"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 15"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\[2mm]
  \\midrule \\midrule
  \\multicolumn{10}{l}{\\bf Incumbency Effect at the Threshold (RD estimates)} \\\\
  \\midrule
  Bandwidth & \\multicolumn{3}{c}{Local Linear}  & \\multicolumn{3}{c}{Local Linear} & \\multicolumn{3}{c}{Local Linear} \\\\
  \\midrule 
1 & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["1"]]["control set1","PE"],2)),"}& \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["1"]]["control set2","PE"],2)),"}  & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["1"]]["control set3","PE"],2)),"} \\\\
 &  \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["1"]]["control set1","SE"],2)),")",sep=""),"}& \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["1"]]["control set2","SE"],2)),")",sep=""),"}  & \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["1"]]["control set3","SE"],2)),")",sep=""),"} \\\\
 &  \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["1"]]["control set1","N"],"}",sep=""),"}& \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["1"]]["control set2","N"],"}",sep=""),"}  & \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["1"]]["control set3","N"],"}",sep=""),"} \\\\[2mm]
2 & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["2"]]["control set1","PE"],2)),"}& \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["2"]]["control set2","PE"],2)),"}  & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["2"]]["control set3","PE"],2)),"} \\\\
 &  \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["2"]]["control set1","SE"],2)),")",sep=""),"}& \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["2"]]["control set2","SE"],2)),")",sep=""),"}  & \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["2"]]["control set3","SE"],2)),")",sep=""),"} \\\\
 &  \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["2"]]["control set1","N"],"}",sep=""),"}& \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["2"]]["control set2","N"],"}",sep=""),"}  & \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["2"]]["control set3","N"],"}",sep=""),"} \\\\[2mm]
5 & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["5"]]["control set1","PE"],2)),"}& \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["5"]]["control set2","PE"],2)),"}  & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["5"]]["control set3","PE"],2)),"} \\\\
 &  \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["5"]]["control set1","SE"],2)),")",sep=""),"}& \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["5"]]["control set2","SE"],2)),")",sep=""),"}  & \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["5"]]["control set3","SE"],2)),")",sep=""),"} \\\\
 &  \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["5"]]["control set1","N"],"}",sep=""),"}& \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["5"]]["control set2","N"],"}",sep=""),"}  & \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["5"]]["control set3","N"],"}",sep=""),"} \\\\[2mm]
\\bottomrule
    \\multicolumn{10}{p{.95\\textwidth}}{\\footnotesize Covariate adjustments are: OLS - Linear regression; Match: One-to-one nearest neighbor matching with replacement and bias adjustment; Weight: Entropy balancing; Local linear: Local linear RD regression. Robust standard errors in parentheses. Window: Sample used to estimate the effect by comparing winners and losers. Bandwidth: Sample used to estimate the RD effect at the threshold. $Y_{i,t+1}$ measured in percentage points, 0--100. }
    \\end{tabular}
    \\end{table}"
    ),file="estimatesRep.tex"
  )
  
# estimates figure
# control sets
figlist <- list()
windows <- seq(1,15,1)

for(i in 1:3){

  store <- matrix(NA,length(windows),3)
  rownames(store) <- windows
  colnames(store) <- c("PE","SE","N")

  
for(h in 1:length(windows)){
  
    # bandwidth
    bw <- windows[h]
    dsub <- na.omit(
      d[abs(d$rv)<bw,
        c("dv","treat","rv",controlsets[[i]])
        ]
    )
    
    # regressions
    form <- as.formula(
      paste("dv~treat+",
            paste(controlsets[[i]],collapse="+")
      )
    )
    out <- lm(form,data=dsub)
    store[h,1:2] <- coeftest(out,vcov = vcovHC(out, type = "HC1"))[2,1:2]
    store[h,3]   <- length(out$residuals)
    
  } 
figlist[[i]] <- store
}

dfig <- figlist[[1]]

pdf("Table3Fig1Rep.pdf",width=9,height=7)
plot(y=dfig[,"PE"],x=windows,pch=19,
     ylim=c(0,12),
     xlim=c(0,15),
     ylab=c("Incumbency Effect Estimate (%)"),
     xlab=c("Effect Window (%)"),
     xaxt="n"
  )
axis(side=1,at=seq(min(windows),max(windows),length.out=length(windows)))

arrows(windows, dfig[,"PE"]-2*dfig[,"SE"]
      ,windows, dfig[,"PE"]+2*dfig[,"SE"]
      , length = 0.15, angle = 90,
       code = 3)

points(y=RDlist[["5"]]["control set1","PE"],
       x=0,pch=15,col="red")

arrows(0, RDlist[["5"]]["control set1","PE"]-2*RDlist[["5"]]["control set1","SE"]
       ,0, RDlist[["5"]]["control set1","PE"]+2*RDlist[["5"]]["control set1","SE"]
       , length = 0.15, angle = 90,col="red",
       code = 3)


arrows(0.1, 4.75
       ,1, 2.5
       , length = 0.10, angle = 35,col="black",
       code = 1)

text(1,2.5,label="RD Estimate at Threshold",pos=4)
dev.off()

## balance stats 
library(tables)
controlsetslab <- list()
controlsetslab[[1]] <- c("Dem Share t-1","Dem Share t-2",
                         "Normal Votet t-1","Normal Vote t-2",
                         "Midterm Slump t")
controlsetslab[[2]] <- controlsetslab[[1]][-4]
controlsetslab[[3]] <- controlsetslab[[1]][c(1,3)]


showvars <- c("type","var","mean.Tr","mean.Co","sdiff.pooled","T.pval","var.ratio")
tab <- bigbalstore[["W 5"]][["Set 1"]][,showvars]
tab$var <- rep(controlsetslab[[1]],3)
tab$type <- rep(c("Unmatched","After Genetic Matching","After Entropy Balancing"),
                each=length(controlsetslab[[1]]))

tab$sdiff.pooled <- tab$sdiff.pooled/100
tab[,-c(1:2)] <- round(tab[,-c(1:2)],2)
colnames(tab) <- c("Adjustment","Covariate","Mean Tr","Mean Co","S.Diff","T.pval","Var.Ratio")


latex(tab,
      file="baltable5.tex",
      #file="",
      label="balancetable5",
      #title='',
      dec=2,rowname=NULL,
      caption=c("Balance Before and After Covariate Adjustment (Window 5\\%)"),
      align=c("llccccc"),
      insert.bottom=c("S.Diff=Standardized difference in means; T-pval=p-value from difference in means test; Var.Ratio: Ratio of variances"))


tab <- bigbalstore[["W 10"]][["Set 1"]][,showvars]
tab$var <- rep(controlsetslab[[1]],3)
tab$type <- rep(c("Unmatched","After Genetic Matching","After Entropy Balancing"),
                each=length(controlsetslab[[1]]))

tab$sdiff.pooled <- tab$sdiff.pooled/100
tab[,-c(1:2)] <- round(tab[,-c(1:2)],2)
colnames(tab) <- c("Adjustment","Covariate","Mean Tr","Mean Co","S.Diff","T.pval","Var.Ratio")

latex(tab,
      file="baltable10.tex",
      #file="",
      label="balancetable10",
      #title='',
      dec=2,rowname=NULL,
      caption=c("Balance Before and After Covariate Adjustment (Window 10\\%)"),
      align=c("llccccc"),
      insert.bottom=c("S.Diff=Standardized difference in means; T-pval=p-value from difference in means test; Var.Ratio: Ratio of variances"))
dev.off()

# plots
library(lattice)


mypal<-c("black","darkgrey","darkgrey")
Cex <- Cex2 <- 1

# plot with SDs
bplot <- function(x,y,...)
{
  panel.abline(v=0, lwd = 1 , lty="solid")
  panel.abline(v=c(-.1,.1), lwd = 2 , lty="dotted")
  panel.abline(h=c(1:nrow(d)), lwd = 1 , lty="dashed", col="gray95")
  panel.xyplot(x,y,...)
}

bplot2 <- function(x,y,...)
{
  panel.abline(v=c(0,1), lwd = 1 , lty="solid")
  panel.abline(v=c(.05,.1), lwd = 1 , lty="dotted")
  panel.abline(h=c(1:nrow(d)), lwd = 1 , lty="dashed", col="gray95")
  panel.xyplot(x,y,...)
}

for(i in c(5,10,15,20)){
  for(s in 1:3){
    
dbal      <- bal[[paste("W",i)]][[paste("Set",s)]]
dbal$type <- factor(dbal$type,levels=unique(dbal$type))
dbal$var  <- factor(dbal$var,levels=unique(dbal$var)[length(unique(dbal$var)):1],
                    labels=controlsetslab[[1]][length(unique(dbal$var)):1])


# plot with Sds
pdf(paste("balSDw",i,"s",s,".pdf",sep=""),width=7,height=7,pointsize=13)
print(
  xyplot(var~round(sdiff.pooled/100,2),data=dbal,groups=type,xlim=c(-.6,.6),
         panel = bplot
         ,par.settings = list(superpose.symbol = list(pch = c(15,19,17),col=mypal,cex=1.5))
         ,xlab=list("standardized difference in means",cex=Cex),ylab="",
         auto.key=T,scales=list(
           y=list(cex=Cex),
           x=list(cex=Cex2,at=c(-.5,-.1,0,.1,.5),labels=c("-.5","-.1","0",".1",".5")))
  )
)
dev.off()

pdf(paste("balpvalw",i,"s",s,".pdf",sep=""),width=7,height=7,pointsize=13)
# plot with p-values
print(
  xyplot(var~round(T.pval,2),data=dbal,groups=type,xlim=c(-.05,1.05),
         panel = bplot2
         ,par.settings = list(superpose.symbol = list(pch = c(15,19,17),col=mypal,cex=1.5))
         ,xlab=list("p-value: difference of means test",cex=Cex),ylab="",
         auto.key=T,scales=list(
           y=list(cex=Cex),
           x=list(cex=Cex2,at=c(0,.05,.1,.5,1),labels=c("0",".05",".1",".5","1")))
  )
)
dev.off()
  }
}

## Table with Gammas

ga <- biggammastore

cat(
  c("\\begin{table}[ht]
    \\centering
    \\caption{{\\bf Sensitivity Analysis for Incumbency Effects in Less Competitive Districts.} Table presents Gamma values from Rosenbaum sensitivity tests for the matching based estimates of the incumbency effects presented in Table 4. The reported Gamma values measure the degree of hidden bias from an unobserved confounder at which the effect estimates would turn insignificant.}
    \\begin{tabular}{ccccccc}
    \\toprule \\toprule
    \\multicolumn{7}{l}{\\bf Sensitivity of Incumbency Effect Estimates in Less Competitive Districts} \\\\
    \\midrule
    & \\multicolumn{2}{c}{\\bf Control Set 1:} & \\multicolumn{2}{c}{\\bf Control Set 2:} & \\multicolumn{2}{c}{\\bf Control Set 3:} \\\\
    & \\multicolumn{2}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{2}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{2}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } \\\\
    & \\multicolumn{2}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{2}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{2}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } \\\\
    & \\multicolumn{2}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{2}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{2}{c}{  } \\\\
    & \\multicolumn{2}{c}{ $\\mathit{Normal \\ Vote}_{t-2}$ } & \\multicolumn{2}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{2}{c}{  } \\\\
    & \\multicolumn{2}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{2}{c}{  } & \\multicolumn{2}{c}{  } \\\\[2mm]
Window  &  Gamma HL  & Gamma p-val & Gamma HL  & Gamma p-val & Gamma HL  & Gamma p-val\\\\
    \\midrule
    5 &",sprintf("%.2f", round(ga[["W 5"]][["Set 1"]][1],2)),"&",sprintf("%.2f",round(ga[["W 5"]][["Set 1"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 5"]][["Set 2"]][1],2)),"&",sprintf("%.2f",round(ga[["W 5"]][["Set 2"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 5"]][["Set 3"]][1],2)),"&",sprintf("%.2f",round(ga[["W 5"]][["Set 3"]][2],2)),"\\\\[2mm]
    10 &",sprintf("%.2f", round(ga[["W 10"]][["Set 1"]][1],2)),"&",sprintf("%.2f", round(ga[["W 10"]][["Set 1"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 10"]][["Set 2"]][1],2)),"&",sprintf("%.2f", round(ga[["W 10"]][["Set 2"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 10"]][["Set 3"]][1],2)),"&",sprintf("%.2f", round(ga[["W 10"]][["Set 3"]][2],2)),"\\\\[2mm]   
    15 &",sprintf("%.2f", round(ga[["W 15"]][["Set 1"]][1],2)),"&",sprintf("%.2f", round(ga[["W 15"]][["Set 1"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 15"]][["Set 2"]][1],2)),"&",sprintf("%.2f", round(ga[["W 15"]][["Set 2"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 15"]][["Set 3"]][1],2)),"&",sprintf("%.2f", round(ga[["W 15"]][["Set 3"]][2],2)),"\\\\
\\bottomrule
    \\multicolumn{7}{p{.95\\textwidth}}{\\footnotesize Gamma HL: The lowest Rosenbaum Gamma at which the lower bound of the Hodges-Lehman point estimate of the incumbency effect remains above zero. Gamma p-val: The lowest Rosenbaum Gamma at which the upper bound of the p-value from a Wilcoxon Sign Rank Test turns insignificant. Window: Sample used to estimate the effect by comparing winners and losers.}
    \\end{tabular}
    \\end{table}"
  ),file="gammas.tex"
  )








### Robustness Check ATTs excluding window 0-5


# effect estimates
biggeststore <- list()
bigbalstore <- list()

for(h in 1:3){
  bwUB <- c(10,15,15)[h]
  bwLB <- c(5,5,10)[h]
  bigstore <- list()
  balstore <- list()
  
  for(i in 1:3){
    
    # bandwidth
    dsub <- na.omit(
      d[ (d$rv > -10 & d$rv < 0) | (d$rv > bwLB & d$rv < bwUB)  ,
        c("dv","treat","rv",controlsets[[i]])
        ]
    )
    
    store <- matrix(NA,3,3)
    rownames(store) <- c("OLS","Match","Ebal")
    colnames(store) <- c("PE","SE","N")
    
    # regressions
    form <- as.formula(
      paste("dv~treat+",
            paste(controlsets[[i]],collapse="+")
      )
    )
    out <- lm(form,data=dsub)
    store[1,1:3] <- c(coeftest(out,vcov = vcovHC(out, type = "HC1"))[2,1:2],
                      length(out$residuals)
    )
    
    # NN Matching
    g.weights <- GenMatch(Tr=dsub$treat, X=dsub[,controlsets[[i]]],estimand="ATT", M=1,print.level=0,pop.size=500)
    out <- Match(Y=dsub$dv, Tr=dsub$treat, X=dsub[,controlsets[[i]]],Weight.matrix=g.weights,
                 estimand = "ATT", M = 1,
                 BiasAdjust = TRUE, replace=TRUE, ties=TRUE,
                 Var.calc = 1)
    store[2,1:3] <- c(out$est,out$se,out$nobs)
    
    # Balance Stats
    balform <- as.formula(
      paste("treat~",
            paste(controlsets[[i]],collapse="+")
      )
    )
    bout <- MatchBalance(balform,data=dsub,match.out=out)
    bout <- data.frame(rbind(
      baltest.collect(matchbal.out=bout,var.names=controlsets[[i]],after=FALSE),
      baltest.collect(matchbal.out=bout,var.names=controlsets[[i]],after=TRUE)
    ),var=rep(controlsets[[i]],2),type=c(
      rep("Unmatched",length(controlsets[[i]])),
      rep("Matched",  length(controlsets[[i]]))
    ),row.names = NULL)
    
    # ebalance
    out <- ebalance(Treatment=dsub$treat,X=dsub[,controlsets[[i]]])
    
    dsub$w <- c(out$w,rep(1,sum(dsub$treat)))
    summary(out$w)
    des <- svydesign(id=~1,weights=dsub$w, data=dsub)
    out <- svyglm(dv ~ treat, design = des)
    summary(out)
    store[3,1:3] <-  c(summary(out)$coef[2,1:2],
                       length(out$residuals))
    
    # balance stats
    bout.eb <- MatchBalance(balform,data=dsub,weights=dsub$w,ks=TRUE)
    bout.eb <- data.frame(baltest.collect(matchbal.out=bout.eb,                                    
                                          var.names=controlsets[[i]],after=FALSE),
                          var=controlsets[[i]],
                          type=rep("Reweighted",length(controlsets[[i]])),
                          row.names = NULL
    )
    bout <- rbind(bout,bout.eb)  
    balstore[[i]] <- bout
    
    bigstore[[i]] <- store
    
  } # close loop over bandwith
  names(balstore) <- paste("Set",1:3)
  bigbalstore[[h]] <- balstore
  
  names(bigstore) <- paste("Set",1:3)
  biggeststore[[h]] <- bigstore
} # close loop over controlsets

names(bigbalstore) <- paste("W",c("5.10","5.15","10.15"))
bal <- bigbalstore

names(biggeststore) <- paste("W",c("5.10","5.15","10.15"))
b <- biggeststore





# create table
cat(
  c("\\begin{table}[ht]
    \\centering
    \\caption{{\\bf Incumbency Effects in Less Competitive Districts Further Away from the Threshold.} Presents incumbency effect estimates in less competitive districts based on the conditional independence assumption for different margins and covariate adjustment methods. The estimates are based on districts where the winners won with margins between 5-10\\%, 5-15\\%, or 10-15\\% and excludes districts where the winner won with narrower margins.}
    \\begin{tabular}{cccccccccc}
    \\toprule \\toprule
   % \\multicolumn{10}{l}{\\bf Incumbency Effect in Less Competitive Districts} \\\\
  %  \\midrule
    & \\multicolumn{3}{c}{\\bf Control Set 1:} & \\multicolumn{3}{c}{\\bf Control Set 2:} & \\multicolumn{3}{c}{\\bf Control Set 3:} \\\\
    & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } \\\\
    & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } \\\\
    & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{3}{c}{  } \\\\
    & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{3}{c}{  } \\\\
    & \\multicolumn{3}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{3}{c}{  } & \\multicolumn{3}{c}{  } \\\\[2mm]
    Margin  & OLS & Match & Weight & OLS & Match & Weight & OLS & Match & Weight\\\\
    \\midrule
    5-10 &",sprintf("%.2f", round(b[["W 5.10"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.10"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.10"]][["Set 1"]]["Ebal","PE"],2)),
        "&",sprintf("%.2f",round(b[["W 5.10"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 5.10"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.10"]][["Set 2"]]["Ebal","PE"],2)),
        "&",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
     &",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
     &",paste("\\emph{N=",b[["W 5.10"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 1"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 5.10"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 2"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 5.10"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\[2mm]
5-15 &",sprintf("%.2f",round(b[["W 5.15"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.15"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 5.15"]][["Set 1"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
     &",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
     &",paste("\\emph{N=",b[["W 5.15"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 1"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 5.15"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 2"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 5.15"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\[2mm]   
10-15 &",sprintf("%.2f",round(b[["W 10.15"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 10.15"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 10.15"]][["Set 1"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
     &",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
     &",paste("\\emph{N=",b[["W 10.15"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 1"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 10.15"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 2"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 10.15"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\
    \\bottomrule
    \\multicolumn{10}{p{.95\\textwidth}}{\\footnotesize Covariate adjustments are: OLS - Linear regression; Match: One-to-one nearest neighbor matching with replacement and bias adjustment; Weight: Entropy balancing. Robust standard errors in parentheses. Margins: Sample of winners used to estimate the effect by comparing winners and losers, e.g. Margin 5-10 means that only districts where the Democrats won with margins between 5 and 10\\% are included. For all margins, the sample of losers consists of districts where the Democrats lost with margins between -10 and 0\\%. $Y_{i,t+1}$ measured in percentage points, 0--100. }
    \\end{tabular}
    \\end{table}"
  ),file="estimatesExternalVal.tex"
  )

# balance stats 
controlsetslab <- list()
controlsetslab[[1]] <- c("Dem Share t-1","Dem Share t-2",
                         "Normal Votet t-1","Normal Vote t-2",
                         "Midterm Slump t")
controlsetslab[[2]] <- controlsetslab[[1]][-4]
controlsetslab[[3]] <- controlsetslab[[1]][c(1,3)]


showvars <- c("type","var","mean.Tr","mean.Co","sdiff.pooled","T.pval","var.ratio")
tab <- bigbalstore[["W 5.10"]][["Set 1"]][,showvars]
tab$var <- rep(controlsetslab[[1]],3)
tab$type <- rep(c("Unmatched","After Genetic Matching","After Entropy Balancing"),
                each=length(controlsetslab[[1]]))

tab$sdiff.pooled <- tab$sdiff.pooled/100
tab[,-c(1:2)] <- round(tab[,-c(1:2)],2)
colnames(tab) <- c("Adjustment","Covariate","Mean Tr","Mean Co","S.Diff","T.pval","Var.Ratio")

latex(tab,
      file="baltable5.10.tex",
      #file="",
      label="balancetable5.10",
      #title='',
      dec=2,rowname=NULL,
      caption=c("Balance Before and After Covariate Adjustment (Margins of 5-10\\%)"),
      align=c("llccccc"),
      insert.bottom=c("S.Diff=Standardized difference in means; T-pval=p-value from difference in means test; Var.Ratio: Ratio of variances"))

tab <- bigbalstore[["W 5.15"]][["Set 1"]][,showvars]
tab$var <- rep(controlsetslab[[1]],3)
tab$type <- rep(c("Unmatched","After Genetic Matching","After Entropy Balancing"),
                each=length(controlsetslab[[1]]))

tab$sdiff.pooled <- tab$sdiff.pooled/100
tab[,-c(1:2)] <- round(tab[,-c(1:2)],2)
colnames(tab) <- c("Adjustment","Covariate","Mean Tr","Mean Co","S.Diff","T.pval","Var.Ratio")

latex(tab,
      file="baltable5.15.tex",
      #file="",
      label="balancetable5.15",
      #title='',
      dec=2,rowname=NULL,
      caption=c("Balance Before and After Covariate Adjustment (Margins 5-15\\%)"),
      align=c("llccccc"),
      insert.bottom=c("S.Diff=Standardized difference in means; T-pval=p-value from difference in means test; Var.Ratio: Ratio of variances"))
dev.off()

tab <- bigbalstore[["W 10.15"]][["Set 1"]][,showvars]
tab$var <- rep(controlsetslab[[1]],3)
tab$type <- rep(c("Unmatched","After Genetic Matching","After Entropy Balancing"),
                each=length(controlsetslab[[1]]))

tab$sdiff.pooled <- tab$sdiff.pooled/100
tab[,-c(1:2)] <- round(tab[,-c(1:2)],2)
colnames(tab) <- c("Adjustment","Covariate","Mean Tr","Mean Co","S.Diff","T.pval","Var.Ratio")

latex(tab,
      file="baltable10.15.tex",
      #file="",
      label="balancetable10.15",
      #title='',
      dec=2,rowname=NULL,
      caption=c("Balance Before and After Covariate Adjustment (Margins 10-15\\%)"),
      align=c("llccccc"),
      insert.bottom=c("S.Diff=Standardized difference in means; T-pval=p-value from difference in means test; Var.Ratio: Ratio of variances"))
dev.off()


#### Code to produce the mechanism plots

rm(list=ls())

### NOTE: csv's are produced in Stata code
### Stata code must be run first to make these!
data <- read.csv("money_for_r.csv")

reg.money <- lm(data$dem_total ~ data$rv)

pdf(file="money.pdf", height=5, width=5)
plot(x=data$rv, y=data$dem_total, yaxt="n", ylab="Log Total Contributions to Democrat", xlab="Democratic Margin (%)", pch=16, col="black", cex=1.2)
abline(reg.money, lwd=2, col="red")
axis(side=2, las=1)
dev.off()

data <- read.csv("qual_for_r.csv")

reg.qual <- lm(data$qual_diff ~ data$rv)

pdf(file="qual.pdf", height=5, width=5)
plot(x=data$rv, y=data$qual_diff, yaxt="n", ylab="Net Quality Differential", xlab="Democratic Margin", pch=16, col="black", cex=1.2)
abline(reg.qual, lwd=2, col="red")
axis(side=2, las=1)
dev.off()


#### Code to produce scare-off estimates


rm(list=ls())

set.seed(1234)

x.size <- 40
span.x <- .5

# load cleaned data
# note that this file is produced in the Stata code
# we have also included a copy of it in the replication data 
d <- read.dta("for_scareoff_estimates.dta")
d <- d[order(d$treat),]

# control sets
controlsets <- list()
controlsets[[1]] <- c("lag","lag2","lag_norm_vote","lag_norm_vote2","midterm")
controlsets[[2]] <- controlsets[[1]][-4]
controlsets[[3]] <- controlsets[[1]][c(1,3)]

# recode dv as net quality differential
d$dv <- d$qual_diff*100

d <- subset(d, dv >= -1)

# partial residual plots

# bandwidth
dsub <- na.omit(
  d[abs(d$rv)<x.size,
    c("dv","treat","rv",controlsets[[1]])
    ]
)

dsub <- dsub[order(dsub$rv),]

dsubright <- dsub[dsub$rv>0,]
dsubleft  <- dsub[dsub$rv<0,]

form1 <- as.formula(
  paste("dv~rv+",
        paste(controlsets[[1]],collapse="+")
  )
)

out    <- lm(form1,data=dsubright)
dsubright$CRresid <- out$resid + coef(out)["rv"]*dsubright$rv

out    <- lm(form1,data=dsubleft)
dsubleft$CRresid <- out$resid + coef(out)["rv"]*dsubleft$rv

dsub <- rbind(dsubleft,dsubright)

#pdf("Table2FigA.pdf",width=9,height=7)
op <- par(mfrow = c(1,2),
          oma = c(5,4,0,0) + 0.1,
          mar = c(0,0,1,1) + 0.1)

plot(y=dsubleft$CRresid,dsubleft$rv,
     xlab="Democratic Margin (%)",
     ylab="Component + Residual: Democratic Margin (%)",cex=.6,
     ylim=c(-2,2),axes = FALSE,xaxs="r",yaxs="i",main="Losers (D=0)", col="gray70")

axis(side = 1,
     at=seq(-x.size,0,5),labels=seq(-x.size,0,5))
     
axis(side = 2, at = seq(-40,40,20) )
segments(x0=0,y0=-40,y1=40)
segments(x0=-x.size-5,x1=0,y0=40,y1=40)
segments(x0=-x.size-5,x1=0,y0=-40,y1=-40)

lo <- predict(loess(CRresid ~ rv, dsubleft ,span=span.x),se=TRUE)
lines(y=lo$fit,dsubleft$rv,lwd=3,col="black")
lines(y=lo$fit+2*lo$se.fit,dsubleft$rv,lwd=2,col="black",lty=2)
lines(y=lo$fit-2*lo$se.fit,dsubleft$rv,lwd=2,col="black",lty=2)
legend("bottomleft",legend=c("Loess Line"),lty=1,lwd=2,col="black")

plot(y=dsubright$CRresid,dsubright$rv,
     xlab="Democratic Margin (%)",
     ylab="",cex=.6,ylim=c(-2,2),axes = FALSE,xaxs="r",yaxs="i",main="Winners (D=1)", col="gray70")

axis(side = 1,
     at=seq(0,x.size,5),labels=seq(0,x.size,5))

segments(x0=0,y0=-40,y1=40)
segments(x0=0,x1=x.size,y0=40,y1=40)
segments(x0=0,x1=x.size,y0=-40,y1=-40)
segments(x0=x.size,x1=x.size,y0=-40,y1=40)

lo <- predict(loess(CRresid ~ rv, dsubright ,span=span.x),se=TRUE)
lines(y=lo$fit,dsubright$rv,lwd=3,col="black")
lines(y=lo$fit+2*lo$se.fit,dsubright$rv,lwd=2,col="black",lty=2)
lines(y=lo$fit-2*lo$se.fit,dsubright$rv,lwd=2,col="black",lty=2)

title(xlab = "Democratic Margin (%)",
      ylab = "Component + Residual: Democratic Margin (%)",
      outer = TRUE, line = 3)

#dev.off()


# effect estimates
biggeststore <- list()
bigbalstore <- list()
biggammastore <- list()

for(h in 1:4){
  bw <- seq(5,20,5)[h]
  bigstore <- list()
  balstore <- list()
  gammastore <- list()
  
 for(i in 1:3){

  # bandwidth
  dsub <- na.omit(
                  d[abs(d$rv)<bw,
                     c("dv","treat","rv",controlsets[[i]])
                    ]
                  )
  
  store <- matrix(NA,3,3)
  rownames(store) <- c("OLS","Match","Ebal")
  colnames(store) <- c("PE","SE","N")
  
  # regressions
  form <- as.formula(
                     paste("dv~treat+",
                           paste(controlsets[[i]],collapse="+")
                          )
                    )
  out <- lm(form,data=dsub)
  store[1,1:3] <- c(coeftest(out,vcov = vcovHC(out, type = "HC1"))[2,1:2],
                    length(out$residuals)
                    )
  
  # NN Matching
  g.weights <- GenMatch(Tr=dsub$treat, X=dsub[,controlsets[[i]]],estimand="ATT", M=1,
                        print.level=0,pop.size=1000)
  out <- Match(Y=dsub$dv, Tr=dsub$treat, X=dsub[,controlsets[[i]]],Weight.matrix=g.weights,
         estimand = "ATT", M = 1,
         BiasAdjust = TRUE, replace=TRUE, ties=TRUE,
         Var.calc = 1)
  store[2,1:3] <- c(out$est,out$se,out$nobs)
  
  # sensitivity
  hl <- hlsens(out, Gamma=10, GammaInc=.1)
  ph <- psens(out, Gamma=10, GammaInc=.1)
  
  # extract highest Gamma at which lower bound of HL estimate is above zero
  # extract highest Gamma at which upper bound of p-value is below .10
  gammas <- c(
    hl$bounds[hl$bounds[,"Lower bound"] > 0,"Gamma"][length(hl$bounds[hl$bounds[,"Lower bound"] > 0,"Gamma"])],
    ph$bounds[ph$bounds[,"Upper bound"] < 0.1,"Gamma"][length(ph$bounds[ph$bounds[,"Upper bound"] < 0.1,"Gamma"])]
    )
  
  
   # Balance Stats
    balform <- as.formula(
     paste("treat~",
          paste(controlsets[[i]],collapse="+")
     )
    )
    bout <- MatchBalance(balform,data=dsub,match.out=out)
    bout <- data.frame(rbind(
         baltest.collect(matchbal.out=bout,var.names=controlsets[[i]],after=FALSE),
         baltest.collect(matchbal.out=bout,var.names=controlsets[[i]],after=TRUE)
         ),var=rep(controlsets[[i]],2),type=c(
                                              rep("Unmatched",length(controlsets[[i]])),
                                              rep("Matched",  length(controlsets[[i]]))
                                              ),row.names = NULL)
  
  # ebalance
  out <- ebalance(Treatment=dsub$treat,X=dsub[,controlsets[[i]]])
  
  dsub$w <- c(out$w,rep(1,sum(dsub$treat)))
  summary(out$w)
  des <- svydesign(id=~1,weights=dsub$w, data=dsub)
  out <- svyglm(dv ~ treat, design = des)
  summary(out)
  store[3,1:3] <-  c(summary(out)$coef[2,1:2],
                     length(out$residuals))

    # balance stats
   bout.eb <- MatchBalance(balform,data=dsub,weights=dsub$w,ks=TRUE)
   bout.eb <- data.frame(baltest.collect(matchbal.out=bout.eb,                                    
                                         var.names=controlsets[[i]],after=FALSE),
              var=controlsets[[i]],
              type=rep("Reweighted",length(controlsets[[i]])),
                         row.names = NULL
                         )
   bout <- rbind(bout,bout.eb)  
   balstore[[i]] <- bout
   bigstore[[i]] <- store
   gammastore[[i]] <- gammas
  
  } # close loop over bandwith
  names(balstore) <- paste("Set",1:3)
  bigbalstore[[h]] <- balstore
  
  names(bigstore) <- paste("Set",1:3)
  biggeststore[[h]] <- bigstore
 
 names(gammastore) <- paste("Set",1:3)
 biggammastore[[h]] <- gammastore
 
} # close loop over controlsets

names(bigbalstore) <- paste("W",seq(5,20,5))
bal <- bigbalstore

names(biggeststore) <- paste("W",seq(5,20,5))
b <- biggeststore

names(biggammastore) <- paste("W",seq(5,20,5))
biggammastore

save.image("ResultsScareOff.RData")

# RDD estimates as a benchmark
bw <- c(1,2,5,10)
# othervars that should not be missing to make sample comparable
RDlist <- list()

store <- matrix(NA,length(controlsets),3)
rownames(store) <- paste("control set",1:3,sep="")
colnames(store) <- c("PE","SE","N")

for(h in 1:length(bw)){

for(i in 1:3){
dsub <- na.omit(
  d[abs(d$rv)< bw[h],
    c("dv","treat","rv","rv_treat",controlsets[[i]])
    ]
)

out <- lm("dv~treat+rv+rv_treat",data=dsub)
store[i,1:3] <- c(coeftest(out,vcov = vcovHC(out, type = "HC1"))[2,1:2],
                  length(out$residuals))
}
RDlist[[h]] <- store
}
names(RDlist) <- bw




# create table
cat(
  c("\\begin{table}[ht]
    \\centering
    \\caption{{\\bf Scare-off Effects in Less Competitive Districts and at the Threshold.} \\label{estimatesScare}The top panel presents scare-off effect estimates in less competitive districts based on the conditional independence assumption for different windows and covariate adjustment methods. The bottom panel presents for comparison the scare-off effect estimates at the threshold based on a regression discontinuity design for different bandwidths.}
     \\begin{tabular}{cccccccccc}
    \\toprule \\toprule
  \\multicolumn{10}{l}{\\bf Scare-off Effect in Less Competitive Districts} \\\\
\\midrule
   & \\multicolumn{3}{c}{\\bf Control Set 1:} & \\multicolumn{3}{c}{\\bf Control Set 2:} & \\multicolumn{3}{c}{\\bf Control Set 3:} \\\\
   & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } \\\\
   & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } \\\\
   & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{3}{c}{  } \\\\
   & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{3}{c}{  } \\\\
   & \\multicolumn{3}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{3}{c}{  } & \\multicolumn{3}{c}{  } \\\\[2mm]
    Window  & OLS & Match & Weight & OLS & Match & Weight & OLS & Match & Weight\\\\
    \\midrule
    5 &",sprintf("%.2f", round(b[["W 5"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 1"]]["Ebal","PE"],2)),
     "&",sprintf("%.2f", round(b[["W 5"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 2"]]["Ebal","PE"],2)),
     "&",sprintf("%.2f", round(b[["W 5"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
      &",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
     "&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
     "&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 5"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
      &",paste("\\emph{N=",b[["W 5"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 1"]]["Ebal","N"],"}",sep=""),
     "&",paste("\\emph{N=",b[["W 5"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 2"]]["Ebal","N"],"}",sep=""),
     "&",paste("\\emph{N=",b[["W 5"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\[2mm]
  10 &",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
      &",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
     "&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
     "&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 10"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
      &",paste("\\emph{N=",b[["W 10"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 1"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 10"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 2"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 10"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\[2mm]   
  15 &",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
     &",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f", round(b[["W 15"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
      &",paste("\\emph{N=",b[["W 15"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 1"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 15"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 2"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 15"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 15"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\[2mm]
  \\midrule \\midrule
  \\multicolumn{10}{l}{\\bf Scare-off Effect at the Threshold (RD estimates)} \\\\
  \\midrule
  Bandwidth & \\multicolumn{3}{c}{Local Linear}  & \\multicolumn{3}{c}{Local Linear} & \\multicolumn{3}{c}{Local Linear} \\\\
  \\midrule 
1 & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["1"]]["control set1","PE"],2)),"}& \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["1"]]["control set2","PE"],2)),"}  & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["1"]]["control set3","PE"],2)),"} \\\\
 &  \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["1"]]["control set1","SE"],2)),")",sep=""),"}& \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["1"]]["control set2","SE"],2)),")",sep=""),"}  & \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["1"]]["control set3","SE"],2)),")",sep=""),"} \\\\
 &  \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["1"]]["control set1","N"],"}",sep=""),"}& \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["1"]]["control set2","N"],"}",sep=""),"}  & \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["1"]]["control set3","N"],"}",sep=""),"} \\\\[2mm]
2 & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["2"]]["control set1","PE"],2)),"}& \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["2"]]["control set2","PE"],2)),"}  & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["2"]]["control set3","PE"],2)),"} \\\\
 &  \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["2"]]["control set1","SE"],2)),")",sep=""),"}& \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["2"]]["control set2","SE"],2)),")",sep=""),"}  & \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["2"]]["control set3","SE"],2)),")",sep=""),"} \\\\
 &  \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["2"]]["control set1","N"],"}",sep=""),"}& \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["2"]]["control set2","N"],"}",sep=""),"}  & \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["2"]]["control set3","N"],"}",sep=""),"} \\\\[2mm]
5 & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["5"]]["control set1","PE"],2)),"}& \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["5"]]["control set2","PE"],2)),"}  & \\multicolumn{3}{c}{",sprintf("%.2f", round(RDlist[["5"]]["control set3","PE"],2)),"} \\\\
 &  \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["5"]]["control set1","SE"],2)),")",sep=""),"}& \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["5"]]["control set2","SE"],2)),")",sep=""),"}  & \\multicolumn{3}{c}{",paste("(",sprintf("%.2f", round(RDlist[["5"]]["control set3","SE"],2)),")",sep=""),"} \\\\
 &  \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["5"]]["control set1","N"],"}",sep=""),"}& \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["5"]]["control set2","N"],"}",sep=""),"}  & \\multicolumn{3}{c}{",paste("\\emph{N=",RDlist[["5"]]["control set3","N"],"}",sep=""),"} \\\\[2mm]
\\bottomrule
    \\multicolumn{10}{p{.95\\textwidth}}{\\footnotesize Covariate adjustments are: OLS - Linear regression; Match: One-to-one nearest neighbor matching with replacement and bias adjustment; Weight: Entropy balancing; Local linear: Local linear RD regression. Robust standard errors in parentheses. Window: Sample used to estimate the effect by comparing winners and losers. Bandwidth: Sample used to estimate the RD effect at the threshold. $Y_{i,t+1}$ measured as $(-100, 0, 100)$. }
    \\end{tabular}
    \\end{table}"
    ),file="estimatesScare.tex"
  )
  
# estimates figure
# control sets
figlist <- list()
windows <- seq(1,15,1)

for(i in 1:3){

  store <- matrix(NA,length(windows),3)
  rownames(store) <- windows
  colnames(store) <- c("PE","SE","N")

  
for(h in 1:length(windows)){
  
    # bandwidth
    bw <- windows[h]
    dsub <- na.omit(
      d[abs(d$rv)<bw,
        c("dv","treat","rv",controlsets[[i]])
        ]
    )
    
    # regressions
    form <- as.formula(
      paste("dv~treat+",
            paste(controlsets[[i]],collapse="+")
      )
    )
    out <- lm(form,data=dsub)
    store[h,1:2] <- coeftest(out,vcov = vcovHC(out, type = "HC1"))[2,1:2]
    store[h,3]   <- length(out$residuals)
    
  } 
figlist[[i]] <- store
}

dfig <- figlist[[1]]

pdf("Table3Fig1a.pdf",width=9,height=7)
plot(y=dfig[,"PE"],x=windows,pch=19,
     ylim=c(-4,30),
     xlim=c(0,15),
     ylab=c("Scare-off Effect Estimate"),
     xlab=c("Effect Window (%)"),
     xaxt="n"
  )
axis(side=1,at=seq(min(windows),max(windows),length.out=length(windows)))

arrows(windows, dfig[,"PE"]-2*dfig[,"SE"]
      ,windows, dfig[,"PE"]+2*dfig[,"SE"]
      , length = 0.15, angle = 90,
       code = 3)

points(y=RDlist[["5"]]["control set1","PE"],
       x=0,pch=15,col="red")

arrows(0, RDlist[["5"]]["control set1","PE"]-2*RDlist[["5"]]["control set1","SE"]
       ,0, RDlist[["5"]]["control set1","PE"]+2*RDlist[["5"]]["control set1","SE"]
       , length = 0.15, angle = 90,col="red",
       code = 3)


arrows(0.1, 25
       ,1, 27
       , length = 0.10, angle = 35,col="black",
       code = 1)

text(1,27,label="RD Estimate at Threshold",pos=4)
dev.off()



## balance stats 
library(tables)
controlsetslab <- list()
controlsetslab[[1]] <- c("Dem Share t-1","Dem Share t-2",
                         "Normal Votet t-1","Normal Vote t-2",
                         "Midterm Slump t")
controlsetslab[[2]] <- controlsetslab[[1]][-4]
controlsetslab[[3]] <- controlsetslab[[1]][c(1,3)]


showvars <- c("type","var","mean.Tr","mean.Co","sdiff.pooled","T.pval","var.ratio")
tab <- bigbalstore[["W 5"]][["Set 1"]][,showvars]
tab$var <- rep(controlsetslab[[1]],3)
tab$type <- rep(c("Unmatched","After Genetic Matching","After Entropy Balancing"),
                each=length(controlsetslab[[1]]))

tab$sdiff.pooled <- tab$sdiff.pooled/100
tab[,-c(1:2)] <- round(tab[,-c(1:2)],2)
colnames(tab) <- c("Adjustment","Covariate","Mean Tr","Mean Co","S.Diff","T.pval","Var.Ratio")


latex(tab,
      file="baltable5.tex",
      #file="",
      label="balancetable5",
      #title='',
      dec=2,rowname=NULL,
      caption=c("Balance Before and After Covariate Adjustment (Window 5\\%)"),
      align=c("llccccc"),
      insert.bottom=c("S.Diff=Standardized difference in means; T-pval=p-value from difference in means test; Var.Ratio: Ratio of variances"))


tab <- bigbalstore[["W 10"]][["Set 1"]][,showvars]
tab$var <- rep(controlsetslab[[1]],3)
tab$type <- rep(c("Unmatched","After Genetic Matching","After Entropy Balancing"),
                each=length(controlsetslab[[1]]))

tab$sdiff.pooled <- tab$sdiff.pooled/100
tab[,-c(1:2)] <- round(tab[,-c(1:2)],2)
colnames(tab) <- c("Adjustment","Covariate","Mean Tr","Mean Co","S.Diff","T.pval","Var.Ratio")

latex(tab,
      file="baltable10.tex",
      #file="",
      label="balancetable10",
      #title='',
      dec=2,rowname=NULL,
      caption=c("Balance Before and After Covariate Adjustment (Window 10\\%)"),
      align=c("llccccc"),
      insert.bottom=c("S.Diff=Standardized difference in means; T-pval=p-value from difference in means test; Var.Ratio: Ratio of variances"))
dev.off()

# plots
library(lattice)


mypal<-c("black","darkgrey","darkgrey")
Cex <- Cex2 <- 1

# plot with SDs
bplot <- function(x,y,...)
{
  panel.abline(v=0, lwd = 1 , lty="solid")
  panel.abline(v=c(-.1,.1), lwd = 2 , lty="dotted")
  panel.abline(h=c(1:nrow(d)), lwd = 1 , lty="dashed", col="gray95")
  panel.xyplot(x,y,...)
}

bplot2 <- function(x,y,...)
{
  panel.abline(v=c(0,1), lwd = 1 , lty="solid")
  panel.abline(v=c(.05,.1), lwd = 1 , lty="dotted")
  panel.abline(h=c(1:nrow(d)), lwd = 1 , lty="dashed", col="gray95")
  panel.xyplot(x,y,...)
}

for(i in c(5,10,15,20)){
  for(s in 1:3){
    
dbal      <- bal[[paste("W",i)]][[paste("Set",s)]]
dbal$type <- factor(dbal$type,levels=unique(dbal$type))
dbal$var  <- factor(dbal$var,levels=unique(dbal$var)[length(unique(dbal$var)):1],
                    labels=controlsetslab[[1]][length(unique(dbal$var)):1])


# plot with Sds
pdf(paste("balSDw",i,"s",s,".pdf",sep=""),width=7,height=7,pointsize=13)
print(
  xyplot(var~round(sdiff.pooled/100,2),data=dbal,groups=type,xlim=c(-.6,.6),
         panel = bplot
         ,par.settings = list(superpose.symbol = list(pch = c(15,19,17),col=mypal,cex=1.5))
         ,xlab=list("standardized difference in means",cex=Cex),ylab="",
         auto.key=T,scales=list(
           y=list(cex=Cex),
           x=list(cex=Cex2,at=c(-.5,-.1,0,.1,.5),labels=c("-.5","-.1","0",".1",".5")))
  )
)
dev.off()

pdf(paste("balpvalw",i,"s",s,".pdf",sep=""),width=7,height=7,pointsize=13)
# plot with p-values
print(
  xyplot(var~round(T.pval,2),data=dbal,groups=type,xlim=c(-.05,1.05),
         panel = bplot2
         ,par.settings = list(superpose.symbol = list(pch = c(15,19,17),col=mypal,cex=1.5))
         ,xlab=list("p-value: difference of means test",cex=Cex),ylab="",
         auto.key=T,scales=list(
           y=list(cex=Cex),
           x=list(cex=Cex2,at=c(0,.05,.1,.5,1),labels=c("0",".05",".1",".5","1")))
  )
)
dev.off()
  }
}

## Table with Gammas

ga <- biggammastore

cat(
  c("\\begin{table}[ht]
    \\centering
    \\caption{{\\bf Sensitivity Analysis for Incumbency Effects in Less Competitive Districts.} Table presents Gamma values from Rosenbaum sensitivity tests for the matching based estimates of the incumbency effects presented in Table 4. The reported Gamma values measure the degree of hidden bias from an unobserved confounder at which the effect estimates would turn insignificant.}
    \\begin{tabular}{ccccccc}
    \\toprule \\toprule
    \\multicolumn{7}{l}{\\bf Sensitivity of Incumbency Effect Estimates in Less Competitive Districts} \\\\
    \\midrule
    & \\multicolumn{2}{c}{\\bf Control Set 1:} & \\multicolumn{2}{c}{\\bf Control Set 2:} & \\multicolumn{2}{c}{\\bf Control Set 3:} \\\\
    & \\multicolumn{2}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{2}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{2}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } \\\\
    & \\multicolumn{2}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{2}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{2}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } \\\\
    & \\multicolumn{2}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{2}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{2}{c}{  } \\\\
    & \\multicolumn{2}{c}{ $\\mathit{Normal \\ Vote}_{t-2}$ } & \\multicolumn{2}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{2}{c}{  } \\\\
    & \\multicolumn{2}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{2}{c}{  } & \\multicolumn{2}{c}{  } \\\\[2mm]
Window  &  Gamma HL  & Gamma p-val & Gamma HL  & Gamma p-val & Gamma HL  & Gamma p-val\\\\
    \\midrule
    5 &",sprintf("%.2f", round(ga[["W 5"]][["Set 1"]][1],2)),"&",sprintf("%.2f",round(ga[["W 5"]][["Set 1"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 5"]][["Set 2"]][1],2)),"&",sprintf("%.2f",round(ga[["W 5"]][["Set 2"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 5"]][["Set 3"]][1],2)),"&",sprintf("%.2f",round(ga[["W 5"]][["Set 3"]][2],2)),"\\\\[2mm]
    10 &",sprintf("%.2f", round(ga[["W 10"]][["Set 1"]][1],2)),"&",sprintf("%.2f", round(ga[["W 10"]][["Set 1"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 10"]][["Set 2"]][1],2)),"&",sprintf("%.2f", round(ga[["W 10"]][["Set 2"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 10"]][["Set 3"]][1],2)),"&",sprintf("%.2f", round(ga[["W 10"]][["Set 3"]][2],2)),"\\\\[2mm]   
    15 &",sprintf("%.2f", round(ga[["W 15"]][["Set 1"]][1],2)),"&",sprintf("%.2f", round(ga[["W 15"]][["Set 1"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 15"]][["Set 2"]][1],2)),"&",sprintf("%.2f", round(ga[["W 15"]][["Set 2"]][2],2)),
    "&",sprintf("%.2f", round(ga[["W 15"]][["Set 3"]][1],2)),"&",sprintf("%.2f", round(ga[["W 15"]][["Set 3"]][2],2)),"\\\\
\\bottomrule
    \\multicolumn{7}{p{.95\\textwidth}}{\\footnotesize Gamma HL: The lowest Rosenbaum Gamma at which the lower bound of the Hodges-Lehman point estimate of the incumbency effect remains above zero. Gamma p-val: The lowest Rosenbaum Gamma at which the upper bound of the p-value from a Wilcoxon Sign Rank Test turns insignificant. Window: Sample used to estimate the effect by comparing winners and losers.}
    \\end{tabular}
    \\end{table}"
  ),file="gammas.tex"
  )



















### Robustness Check ATTs excluding window 0-5


# effect estimates
biggeststore <- list()
bigbalstore <- list()

for(h in 1:3){
  bwUB <- c(10,15,15)[h]
  bwLB <- c(5,5,10)[h]
  bigstore <- list()
  balstore <- list()
  
  for(i in 1:3){
    
    # bandwidth
    dsub <- na.omit(
      d[ (d$rv > -10 & d$rv < 0) | (d$rv > bwLB & d$rv < bwUB)  ,
        c("dv","treat","rv",controlsets[[i]])
        ]
    )
    
    store <- matrix(NA,3,3)
    rownames(store) <- c("OLS","Match","Ebal")
    colnames(store) <- c("PE","SE","N")
    
    # regressions
    form <- as.formula(
      paste("dv~treat+",
            paste(controlsets[[i]],collapse="+")
      )
    )
    out <- lm(form,data=dsub)
    store[1,1:3] <- c(coeftest(out,vcov = vcovHC(out, type = "HC1"))[2,1:2],
                      length(out$residuals)
    )
    
    # NN Matching
    g.weights <- GenMatch(Tr=dsub$treat, X=dsub[,controlsets[[i]]],estimand="ATT", M=1,print.level=0,pop.size=500)
    out <- Match(Y=dsub$dv, Tr=dsub$treat, X=dsub[,controlsets[[i]]],Weight.matrix=g.weights,
                 estimand = "ATT", M = 1,
                 BiasAdjust = TRUE, replace=TRUE, ties=TRUE,
                 Var.calc = 1)
    store[2,1:3] <- c(out$est,out$se,out$nobs)
    
    # Balance Stats
    balform <- as.formula(
      paste("treat~",
            paste(controlsets[[i]],collapse="+")
      )
    )
    bout <- MatchBalance(balform,data=dsub,match.out=out)
    bout <- data.frame(rbind(
      baltest.collect(matchbal.out=bout,var.names=controlsets[[i]],after=FALSE),
      baltest.collect(matchbal.out=bout,var.names=controlsets[[i]],after=TRUE)
    ),var=rep(controlsets[[i]],2),type=c(
      rep("Unmatched",length(controlsets[[i]])),
      rep("Matched",  length(controlsets[[i]]))
    ),row.names = NULL)
    
    # ebalance
    out <- ebalance(Treatment=dsub$treat,X=dsub[,controlsets[[i]]])
    
    dsub$w <- c(out$w,rep(1,sum(dsub$treat)))
    summary(out$w)
    des <- svydesign(id=~1,weights=dsub$w, data=dsub)
    out <- svyglm(dv ~ treat, design = des)
    summary(out)
    store[3,1:3] <-  c(summary(out)$coef[2,1:2],
                       length(out$residuals))
    
    # balance stats
    bout.eb <- MatchBalance(balform,data=dsub,weights=dsub$w,ks=TRUE)
    bout.eb <- data.frame(baltest.collect(matchbal.out=bout.eb,                                    
                                          var.names=controlsets[[i]],after=FALSE),
                          var=controlsets[[i]],
                          type=rep("Reweighted",length(controlsets[[i]])),
                          row.names = NULL
    )
    bout <- rbind(bout,bout.eb)  
    balstore[[i]] <- bout
    
    bigstore[[i]] <- store
    
  } # close loop over bandwith
  names(balstore) <- paste("Set",1:3)
  bigbalstore[[h]] <- balstore
  
  names(bigstore) <- paste("Set",1:3)
  biggeststore[[h]] <- bigstore
} # close loop over controlsets

names(bigbalstore) <- paste("W",c("5.10","5.15","10.15"))
bal <- bigbalstore

names(biggeststore) <- paste("W",c("5.10","5.15","10.15"))
b <- biggeststore





# create table
cat(
  c("\\begin{table}[ht]
    \\centering
    \\caption{{\\bf Incumbency Effects in Less Competitive Districts Further Away from the Threshold.} \\label{estimatesScare}Presents incumbency effect estimates in less competitive districts based on the conditional independence assumption for different margins and covariate adjustment methods. The estimates are based on districts where the winners won with margins between 5-10\\%, 5-15\\%, or 10-15\\% and excludes districts where the winner won with narrower margins.}
    \\begin{tabular}{cccccccccc}
    \\toprule \\toprule
   % \\multicolumn{10}{l}{\\bf Incumbency Effect in Less Competitive Districts} \\\\
  %  \\midrule
    & \\multicolumn{3}{c}{\\bf Control Set 1:} & \\multicolumn{3}{c}{\\bf Control Set 2:} & \\multicolumn{3}{c}{\\bf Control Set 3:} \\\\
    & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-1}$ } \\\\
    & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Dem \\ Share}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } \\\\
    & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-1}$ } & \\multicolumn{3}{c}{  } \\\\
    & \\multicolumn{3}{c}{ $\\mathit{Normal \\ Vote}_{t-2}$ } & \\multicolumn{3}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{3}{c}{  } \\\\
    & \\multicolumn{3}{c}{ $\\mathit{Midterm \\ Slump}_{t}$ } & \\multicolumn{3}{c}{  } & \\multicolumn{3}{c}{  } \\\\[2mm]
    Margin  & OLS & Match & Weight & OLS & Match & Weight & OLS & Match & Weight\\\\
    \\midrule
    5-10 &",sprintf("%.2f", round(b[["W 5.10"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.10"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.10"]][["Set 1"]]["Ebal","PE"],2)),
        "&",sprintf("%.2f",round(b[["W 5.10"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f", round(b[["W 5.10"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.10"]][["Set 2"]]["Ebal","PE"],2)),
        "&",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
     &",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.10"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
     &",paste("\\emph{N=",b[["W 5.10"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 1"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 5.10"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 2"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 5.10"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.10"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\[2mm]
5-15 &",sprintf("%.2f",round(b[["W 5.15"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.15"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 5.15"]][["Set 1"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
     &",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 5.15"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
     &",paste("\\emph{N=",b[["W 5.15"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 1"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 5.15"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 2"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 5.15"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 5.15"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\[2mm]   
10-15 &",sprintf("%.2f",round(b[["W 10.15"]][["Set 1"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 10.15"]][["Set 1"]]["Match","PE"],2)),"&",sprintf("%.2f", round(b[["W 10.15"]][["Set 1"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["Ebal","PE"],2)),
    "&",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["OLS","PE"],2)),"&",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["Match","PE"],2)),"&",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["Ebal","PE"],2)),"\\\\
     &",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 1"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 1"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 1"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 2"]]["Ebal","SE"],2)),")",sep=""),
    "&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["OLS","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["Match","SE"],2)),")",sep=""),"&",paste("(",sprintf("%.2f",round(b[["W 10.15"]][["Set 3"]]["Ebal","SE"],2)),")",sep=""),"\\\\
     &",paste("\\emph{N=",b[["W 10.15"]][["Set 1"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 1"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 1"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 10.15"]][["Set 2"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 2"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 2"]]["Ebal","N"],"}",sep=""),
    "&",paste("\\emph{N=",b[["W 10.15"]][["Set 3"]]["OLS","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 3"]]["Match","N"],"}",sep=""),"&",paste("\\emph{N=",b[["W 10.15"]][["Set 3"]]["Ebal","N"],"}",sep=""),"\\\\
    \\bottomrule
    \\multicolumn{10}{p{.95\\textwidth}}{\\footnotesize Covariate adjustments are: OLS - Linear regression; Match: One-to-one nearest neighbor matching with replacement and bias adjustment; Weight: Entropy balancing. Robust standard errors in parentheses. Margins: Sample of winners used to estimate the effect by comparing winners and losers, e.g. Margin 5-10 means that only districts where the Democrats won with margins between 5 and 10\\% are included. For all margins, the sample of losers consists of districts where the Democrats lost with margins between -10 and 0\\%. $Y_{i,t+1}$ measured in percentage points, 0--100. }
    \\end{tabular}
    \\end{table}"
  ),file="estimatesScareExternal.tex"
  )

# balance stats 
controlsetslab <- list()
controlsetslab[[1]] <- c("Dem Share t-1","Dem Share t-2",
                         "Normal Votet t-1","Normal Vote t-2",
                         "Midterm Slump t")
controlsetslab[[2]] <- controlsetslab[[1]][-4]
controlsetslab[[3]] <- controlsetslab[[1]][c(1,3)]


showvars <- c("type","var","mean.Tr","mean.Co","sdiff.pooled","T.pval","var.ratio")
tab <- bigbalstore[["W 5.10"]][["Set 1"]][,showvars]
tab$var <- rep(controlsetslab[[1]],3)
tab$type <- rep(c("Unmatched","After Genetic Matching","After Entropy Balancing"),
                each=length(controlsetslab[[1]]))

tab$sdiff.pooled <- tab$sdiff.pooled/100
tab[,-c(1:2)] <- round(tab[,-c(1:2)],2)
colnames(tab) <- c("Adjustment","Covariate","Mean Tr","Mean Co","S.Diff","T.pval","Var.Ratio")

latex(tab,
      file="baltable5.10.tex",
      #file="",
      label="balancetable5.10",
      #title='',
      dec=2,rowname=NULL,
      caption=c("Balance Before and After Covariate Adjustment (Margins of 5-10\\%)"),
      align=c("llccccc"),
      insert.bottom=c("S.Diff=Standardized difference in means; T-pval=p-value from difference in means test; Var.Ratio: Ratio of variances"))

tab <- bigbalstore[["W 5.15"]][["Set 1"]][,showvars]
tab$var <- rep(controlsetslab[[1]],3)
tab$type <- rep(c("Unmatched","After Genetic Matching","After Entropy Balancing"),
                each=length(controlsetslab[[1]]))

tab$sdiff.pooled <- tab$sdiff.pooled/100
tab[,-c(1:2)] <- round(tab[,-c(1:2)],2)
colnames(tab) <- c("Adjustment","Covariate","Mean Tr","Mean Co","S.Diff","T.pval","Var.Ratio")

latex(tab,
      file="baltable5.15.tex",
      #file="",
      label="balancetable5.15",
      #title='',
      dec=2,rowname=NULL,
      caption=c("Balance Before and After Covariate Adjustment (Margins 5-15\\%)"),
      align=c("llccccc"),
      insert.bottom=c("S.Diff=Standardized difference in means; T-pval=p-value from difference in means test; Var.Ratio: Ratio of variances"))
dev.off()

tab <- bigbalstore[["W 10.15"]][["Set 1"]][,showvars]
tab$var <- rep(controlsetslab[[1]],3)
tab$type <- rep(c("Unmatched","After Genetic Matching","After Entropy Balancing"),
                each=length(controlsetslab[[1]]))

tab$sdiff.pooled <- tab$sdiff.pooled/100
tab[,-c(1:2)] <- round(tab[,-c(1:2)],2)
colnames(tab) <- c("Adjustment","Covariate","Mean Tr","Mean Co","S.Diff","T.pval","Var.Ratio")

latex(tab,
      file="baltable10.15.tex",
      #file="",
      label="balancetable10.15",
      #title='',
      dec=2,rowname=NULL,
      caption=c("Balance Before and After Covariate Adjustment (Margins 10-15\\%)"),
      align=c("llccccc"),
      insert.bottom=c("S.Diff=Standardized difference in means; T-pval=p-value from difference in means test; Var.Ratio: Ratio of variances"))
dev.off()








